首页 > 编程语言 > 详细

java 多线程 day05 线程范围内的数据共享

时间:2017-12-03 22:34:25      阅读:242      评论:0      收藏:0      [点我收藏+]
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* Created by chengtao on 17/12/3.
* 线程范围内的数据共享:即模块从不同的线程获取到的值是不一样的
* 可以通过 hashMap<thread,data> 来将线程和对应的值通过map来区分
*/

public class Thread0501_ThreadScopeShareData {

private static int data = 0;
public static void main(String[] args) {
for(int i=0;i<2;i++){
new Thread(new Runnable(){
public void run() {
data = new Random().nextInt();
System.out.println(Thread.currentThread().getName()
+ " has put data :" + data);
new A().get();
new B().get();
}
}).start();
}
}

static class A{
public void get(){
System.out.println("A from " + Thread.currentThread().getName() + " get data :" + data);
}
}

static class B{
public void get(){
System.out.println("B from " + Thread.currentThread().getName() + " get data :" + data);
}
}
}




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

/**
* Created by chengtao on 17/12/3.
* 线程间的数据共享
*/



public class Thread0502_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<2;i++){
new Thread(new Runnable(){
public void run() {
int data = new Random().nextInt();
System.out.println(Thread.currentThread().getName()
+ " has put data :" + data);
threadData.put(Thread.currentThread(), data);
new A().get();
new B().get();
}
}).start();
}
}

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);
}
}
}

java 多线程 day05 线程范围内的数据共享

原文:http://www.cnblogs.com/ctaixw/p/7967538.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!