ThreadLocal下
传送门:http://www.nowcoder.com/discuss/18817?type=0&order=0&pos=6&page=0
仔细分析就可以发现,线程之间共享的static变量无法保证线程安全。
那么如何保证线程安全呢?
先看另一种实现:
public class TestB implements Sequence{ private static ThreadLocal<Integer> numberContainer=new Threadlocal<Integer>(){ protected Integer initialValue(){ return 0; } }; public int getNumber(){ numberContainer.set(numberContainer.get()+1); return numberContainer.get(); } public static void main(String[] args){ TestB squenceB=new Clinet(); Client thread1=new Clinet(squenceB); Client thread2=new Clinet(squenceB); Client thread3=new Clinet(squenceB); thread1.start(); thread2.start(); thread3.start(); } }
解决了
三个线程输出的都是
1
2
3
#Java工程师#