張孝祥java多線程視頻筆記----線程範圍內共享變量

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

//線程範圍內的共享變量
/*線程範圍內的共享變量
     * 作用:線程範圍內的共享變量是指對同一個變量,幾個線程同時對它進行寫和讀操作,
     * 而同一個線程讀到的數據就是它自己寫進去的數據。
*/

public class Test5 {
// 內部類需要訪問外部類的局部變量,則必須使用final或者static修飾
   private static Map<Thread,Integer> map=new HashMap<Thread, Integer>();
  
   public static void main(String args[]){
 
 
  for(int i=0;i<2;i++)
  new Thread(new Runnable(){
  public void run() {
   int data=new Random().nextInt();
   System.out.println(Thread.currentThread().getName()+data);
   map.put(Thread.currentThread(), data);
      new A().get();
      new B().get();
   
  }
  
  }).start();
   }
 
   static class A{
    public void get(){
     System.out.println(Thread.currentThread().getName()+": "+map.get(Thread.currentThread()));
    }
   }
   static class B{
    public void get(){
     System.out.println(Thread.currentThread().getName()+": "+map.get(Thread.currentThread()));
    }
   }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章