public class ThreadLocalMain { private static ThreadLocal<Integer> value = new ThreadLocal<Integer>() { @Override protected Integer initialValue(){ return 0; } }; class TestThread implements Runnable { private int index; public TestThread(int index) { this.index = index; } public void run() { System.out.println("线程“+index +"的初始Value:" + value.get()); for(int i=0;i<10;i++) { value.set(value.get()+i); } System.out.println("线程“+index +"的累加Value:" + value.get()); } public static void main(String [] args) { ThreadLocalMain main = new ThreadLocalMain(); for(int i=0;i<5;i++) { TestThread testThread = main.new TestThread(i); new Thread(testThread).start(); } } } }
关于ThreadLocal的使用请参见:http://ifeve.com/java-theadlocal/
时间: 2024-10-12 18:42:05