/** * Created by brian on 2016/2/4. */ publicclassThreadScopeShareData{ //准备一个哈希表,为每个线程准备数据 privatestatic Map<Thread,Integer> threadData = new HashMap<>(); publicstaticvoidmain(String[] args){ for(int i=0;i<2;i++){ new Thread( new Runnable() { @Override publicvoidrun(){ int data = new Random().nextInt(); threadData.put(Thread.currentThread(),data); System.out.println(Thread.currentThread()+" put data:"+data); new A().get(); new B().get(); } }).start(); } } staticclassA{ publicvoidget(){ int data = threadData.get(Thread.currentThread()); System.out.println("A from "+Thread.currentThread()+" get data "+data); } }
staticclassB{ publicvoidget(){ int data = threadData.get(Thread.currentThread()); System.out.println("B from "+Thread.currentThread()+" get data "+data); } } }
上述代码偶尔会报异常:
1 2 3 4
Exception in thread "Thread-0" java.lang.NullPointerException at com.iot.thread.ThreadScopeShareData$A.get(ThreadScopeShareData.java:29) at com.iot.thread.ThreadScopeShareData$1.run(ThreadScopeShareData.java:21) at java.lang.Thread.run(Thread.java:745)
/** * Created by brian on 2016/2/4. */ publicclassThreadLocalTest{ privatestatic ThreadLocal<Integer> threadInger = new ThreadLocal<>(); publicstaticvoidmain(String[] args){ for(int i=0;i<2;i++){ new Thread(new Runnable() { @Override publicvoidrun(){ int data = new Random().nextInt(100); threadInger.set(data); System.out.println(Thread.currentThread()+" put data:"+data); MyThreadScopeData.getThreadInstance().setName(Thread.currentThread().toString()); MyThreadScopeData.getThreadInstance().setAge(data%10); new A().get(); new B().get(); } }).start(); } } staticclassA{ publicvoidget(){ int data = threadInger.get(); System.out.println("A from "+Thread.currentThread()+" get data "+data); MyThreadScopeData myThreadScopeData = MyThreadScopeData.getThreadInstance(); System.out.println("A from "+myThreadScopeData);
} }
staticclassB{ publicvoidget(){ int data = threadInger.get(); System.out.println("B from "+Thread.currentThread()+" get data "+data); MyThreadScopeData myThreadScopeData = MyThreadScopeData.getThreadInstance(); System.out.println("B from "+myThreadScopeData); } } }
/** * Created by brian on 2016/2/4. */ publicclassMutiThreadShareData{
privatestatic MutiShareData mutiShareData = new MutiShareData();
publicstaticvoidmain(String[] args){
for(int i=0;i<3;i++){ new Thread( new Runnable() { @Override publicvoidrun(){ System.out.println(Thread.currentThread()+":{j from "+ mutiShareData.getJ()+" + to: "+mutiShareData.increment()+"}"); } } ).start(); }
for(int i=0;i<2;i++){ new Thread( new Runnable() { @Override publicvoidrun(){ System.out.println(Thread.currentThread()+":{j from "+ mutiShareData.getJ()+" - to: "+mutiShareData.decrement()+"}"); } } ).start(); } }