关闭

java 之 线程间变量共享

标签: javarandomintegerclassthreadimport
6019人阅读 评论(0) 收藏 举报
分类:
import java.util.Random;

public class StaticTest {
	
	private static int data = 0;

	public static void main(String[] args) {
		//开三个线程
				for(int i=0;i<3;i++) {
					new Thread(new Runnable() {

						@Override
						public void run() {
							//每个线程data值都一样,下边的程序有解释
						 data = new Random().nextInt();
							System.out.println(Thread.currentThread().getName() + " has put data :"+ data);
						}
						
					}).start();
				}
	}

}

运行结果:

Thread-1 has put data :367396051
Thread-2 has put data :367396051
Thread-0 has put data :367396051

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


public class ThreadScopeShareData {

	//静态,会造成一样的随机值,此处有点不理解
	private static int data = 0;
	//以线程作为key
	private static Map<Thread,Integer> threadData = new HashMap<Thread, Integer>();
	
	public static void main(String[] args) {
		//开三个线程
		for(int i=0;i<3;i++) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					//每个线程data值都一样,因为是静态变量,一改全改,最后的结果跟最后的线程data值一样
					//被后来的线程data值覆盖了,因为静态变量只有一份
//					data = new Random().nextInt();
					//这样就不同了
					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);
		}
	}
}


map模拟了ThreadLocal。

运行结果:

Thread-0 has put data :1500573848
Thread-2 has put data :1307429900
Thread-1 has put data :-1173968999
A from  Thread-1 get data : -1173968999
A from  Thread-0 get data : 1500573848
A from  Thread-2 get data : 1307429900
B from  Thread-1 get data : -1173968999
B from  Thread-0 get data : 1500573848
B from  Thread-2 get data : 1307429900


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:616029次
    • 积分:7138
    • 等级:
    • 排名:第3154名
    • 原创:183篇
    • 转载:80篇
    • 译文:0篇
    • 评论:123条
    文章分类
    最新评论