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();
    	}
    }
    
  • 相关阅读:
    十一.状态设计模式
    十. 享元设计模式
    Orcale(一)概念
    java类加载器
    spring中的事务管理机制
    spring中的annotation注解类配置
    countDownLatch和Semaphore用于多线程
    布隆过滤器
    mybatis-genator自动生成的mapper中模糊查询使用方法
    java中的异常
  • 原文地址:https://www.cnblogs.com/joeCqupt/p/6826984.html
Copyright © 2011-2022 走看看