java实现线程范围内数据共享:
Thread.crruntThread()
使用HashMap<Thread,Object>
经过A,B,C三个模块都是获得同一个值
执行结果
java中提供了Threadlocal类已经实现了该
Threadlocal<Integer> tl=new Threadlocal<Integer>()
t1.get();
[b]使得该类在创建对象时候直接就是同一个线程同一个对象 对象不同线程不同,就像你登录后获得你的当前登录的用户时候不会获得别人的用户[/b]
[b]来点实际的:[/b]
这个大家应该再熟悉不过了。我们使用多个线程来测试一下
测试结果是:同一个线程的UserService是相同的,不论是在A或者B中都能够获得
Thread.crruntThread()
使用HashMap<Thread,Object>
经过A,B,C三个模块都是获得同一个值
public class ThreadDemo20 {
private static HashMap<Thread,Integer> data=new HashMap<Thread,Integer>();
static class A{
public void getData(){
Thread t=Thread.currentThread();
int value=data.get(t);
System.out.println(t.getName()+" from A getData "+value);
}
}
static class B{
public void getData(){
Thread t=Thread.currentThread();
int value=data.get(t);
System.out.println(t.getName()+" from B getData "+value);
}
}
static class C{
public void getData(){
Thread t=Thread.currentThread();
int value=data.get(t);
System.out.println(t.getName()+" from C getData "+value);
}
}
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
@Override
public void run() {
int value=new Random().nextInt(1000);
data.put(Thread.currentThread(), value);
A a1=new A();
a1.getData();
B b1=new B();
b1.getData();
C c1=new C();
c1.getData();
}
}).start();;
}
}
}
执行结果
Thread-1 from A getData 521
Thread-1 from B getData 521
Thread-1 from C getData 521
Thread-0 from A getData 925
Thread-0 from B getData 925
Thread-0 from C getData 925
java中提供了Threadlocal类已经实现了该
Threadlocal<Integer> tl=new Threadlocal<Integer>()
t1.get();
[b]使得该类在创建对象时候直接就是同一个线程同一个对象 对象不同线程不同,就像你登录后获得你的当前登录的用户时候不会获得别人的用户[/b]
[b]来点实际的:[/b]
public class UserService {
private static ThreadLocal<UserService> tl = new ThreadLocal<UserService>();
private UserService() {}
public static UserService getInstance() {
UserService us = tl.get();
if (us == null) {
us = new UserService();
tl.set(us);
}
return us;
}
}
这个大家应该再熟悉不过了。我们使用多个线程来测试一下
public class UserServiceTest {
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
new Thread(new Runnable() {
@Override
public void run() {
A a=new A();
a.print();
B b=new B();
b.print();
}
}).start();
}
}
static class A {
public void print() {
UserService us = UserService.getInstance();
System.out.println("from A "+Thread.currentThread().getName() + "..." + us);
}
}
static class B {
public void print() {
UserService us = UserService.getInstance();
System.out.println("from B "+Thread.currentThread().getName() + "..." + us);
}
}
}
测试结果是:同一个线程的UserService是相同的,不论是在A或者B中都能够获得
from A Thread-3...thread.UserService@787d6a
from A Thread-0...thread.UserService@1f4cbee
from A Thread-1...thread.UserService@1f4cbee
from A Thread-2...thread.UserService@787d6a
from B Thread-2...thread.UserService@787d6a
from B Thread-3...thread.UserService@787d6a
from B Thread-0...thread.UserService@1f4cbee
from B Thread-1...thread.UserService@1f4cbee