ThreadLocalの例
1318 ワード
ThreadLocalの例を見ると、テストが2つのスレッドを起動したことがわかります.この場合、threadLocalは2つのスレッドにそれぞれ1つの値を持ち、互いに影響しません.threadlocalの中のデータは現在のスレッドに関連しており、threadlocalの中で取ったデータは現在のスレッドのデータである.public class threadLocalTest {
static class A { public void get(){ Integer data=x.get(); System.out.println("A from "+Thread.currentThread().getName()+“data:”+data); } }
}
実行結果:
Thread-0 has put data:1161243174 A from Thread-0 data:1161243174 B from Thread-0 data:1161243174
Thread-1 has put data:1237148231 A from Thread-1 data:1237148231 B from Thread-1 data:1237148231
private static ThreadLocal x=new ThreadLocal<>();
public static void main(String[] args) {
for(int i=0;i<2;i++){
new Thread(new Runnable() {
@Override
public void run() {
Integer data= new Random().nextInt();
System.out.println(Thread.currentThread().getName()+"has put data:"+data);
x.set(data);
new A().get();
new B().get();
}
}).start();
}
}
static class A { public void get(){ Integer data=x.get(); System.out.println("A from "+Thread.currentThread().getName()+“data:”+data); } }
static class B {
public void get(){
Integer data=x.get();
System.out.println("B from "+Thread.currentThread().getName()+"data:"+data);
}
}
}
実行結果:
Thread-0 has put data:1161243174 A from Thread-0 data:1161243174 B from Thread-0 data:1161243174
Thread-1 has put data:1237148231 A from Thread-1 data:1237148231 B from Thread-1 data:1237148231