線程範圍的數據共享(用HashMap版)
阿新 • • 發佈:2018-08-23
ring static ktr ide shared auto gen ride nts
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class ThreadScopeShareData {
private static int data = 0;
private static Map<Thread, Integer> threadData = new HashMap<Thread, Integer>();
public static void main(String[] args) {
for(int i=0;i<40;i++){
new Thread(new Runnable(){
@Override
public void run() {
data = new Random().nextInt();
System.out.println(Thread.currentThread().getName()
+ " has put data :" + data);
//把每個線程的數據單獨保存起來 否則當線程創建後run方法運行一半
//其他線程可能會修改了本線程的數據
threadData.put(Thread.currentThread(), data);
new A().get();
new B().get();
}
}).start();
/* try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
static class A{
public void get(){
int data = threadData.get(Thread.currentThread());
System.out.println("A from " + Thread.currentThread().getName()
+ " get data :" + data);
}
}
static class B{
public void get(){
int data = threadData.get(Thread.currentThread());
System.out.println("B from " + Thread.currentThread().getName()
+ " get data :" + data);
}
}
}
線程範圍的數據共享(用HashMap版)