您的位置:首页 > 编程语言 > Java开发

张孝祥java多线程视频笔记----线程范围内共享变量

2013-08-19 19:29 337 查看
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()));

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: