现在的位置: 首页 > 综合 > 正文

张孝祥实现线程范围内数据共享(学习笔记)

2014年09月05日 ⁄ 综合 ⁄ 共 839字 ⁄ 字号 评论关闭
package cn.javaious.concurrence;

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

public class ThreadScopeShareData {
	
	private static Map<Thread, Integer> threadData = new HashMap<Thread, Integer>();
	public static void main(String[] args) {
		for (int i = 0; i < 4; i++) {

			new Thread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					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()
					+" has put data :"+data);
		}
	}
	static class B {
		public void get() {
			int data = threadData.get(Thread.currentThread());
			System.out.println("B from " + Thread.currentThread().getName()
					+" has put data :"+data);
		}
	}
}

抱歉!评论已关闭.