多线程学习(十)

线程本地存储

防止任务在共享资源上产生冲突的第二种方式就是根除对线程的共享,线程本地存储一种自动化机制。可以为使用相同变量的每个不同的线程都创建不同的存储。如果你有5个线程要使用变量X所表示的对象,那么线程本地存储就会生成5个用于x的不同的存储块。主要是 可以使得线程与状态关联起来。

public class ThreadLocalVariableHolder {
	private static ThreadLocal<Integer> value = new ThreadLocal<Integer>() {

		@Override
		protected Integer initialValue() {
			// TODO Auto-generated method stub
			return 0;
		}

	};

	public static void increment() {
		value.set(value.get() + 1);
		
	}

	public static Integer get() {
		return value.get();
	}

	public static void set(int a) {
		value.set(a);
	}
}
public class ThreadlocalTest implements Runnable {
	private int initValue;

	public ThreadlocalTest(int initValue) {
		super();
		this.initValue = initValue;
		ThreadLocalVariableHolder.set(initValue);

	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (!Thread.currentThread().isInterrupted()) {
			ThreadLocalVariableHolder.increment();
			System.out.println(this);
		}
	}

	@Override
	public String toString() {
		return "#id(" + Thread.currentThread().getId() + ")" + ThreadLocalVariableHolder.get();
	}

	public static void main(String[] args) throws Exception {
		ExecutorService exec = Executors.newCachedThreadPool();
		Runnable target = new ThreadlocalTest(0);
		for (int i = 0; i < 5; i++) {
			exec.execute(target);
		}
		
		TimeUnit.MILLISECONDS.sleep(50);
		
		exec.shutdownNow();
	}
}
posted @ 2017-05-08 19:50  风中小蘑菇  阅读(103)  评论(0编辑  收藏  举报