zoukankan      html  css  js  c++  java
  • 多线程学习(十)

    线程本地存储

    防止任务在共享资源上产生冲突的第二种方式就是根除对线程的共享,线程本地存储一种自动化机制。可以为使用相同变量的每个不同的线程都创建不同的存储。如果你有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();
    	}
    }
    
  • 相关阅读:
    UWP开发必备:常用数据列表控件汇总比较
    CodeForces 372 A. Counting Kangaroos is Fun
    ubuntu 13.10 eclipse 菜单栏不可用的问题
    Codeforces Round #219(Div. 2)373 B. Making Sequences is Fun(二分+找规律)
    Git/Github使用方法小记
    Ubuntu 下jdk的安装
    VIM简明教程
    codeforces 371 C-Hamburgers
    codeforces 371A K-Periodic Array
    计算机网络中IP地址和MAC地址
  • 原文地址:https://www.cnblogs.com/joeCqupt/p/6826984.html
Copyright © 2011-2022 走看看