ETHAN IN IT

Lost in it

java 之 线程间变量共享

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


阅读更多
个人分类: java
上一篇移动计费系统学习(五)
下一篇深入Java虚拟机JVM类加载初始化学习笔记
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭