1、Sequence类
package self.inter; public interface Sequence { int getNumber(); }
2、SequenceB
package self.inter.impl; import self.inter.Sequence; import self.thread.ClientThread; /** * 这个类线程安全 * * @author xujl * */ public class SequenceB implements Sequence { private static int number = 0; private static ThreadLocal<Integer> numberContainer = new ThreadLocal<Integer>(){ @Override protected Integer initialValue(){ return 0; } }; public int getNumber() { numberContainer.set(numberContainer.get()+1); return numberContainer.get(); } public static void main(String[] args) { Sequence sequence = new SequenceB(); ClientThread ct1 = new ClientThread(sequence); ClientThread ct2 = new ClientThread(sequence); ClientThread ct3 = new ClientThread(sequence); ct1.start(); ct2.start(); ct3.start(); } }
3、SequenceApackage self.inter.impl; import self.inter.Sequence; import self.thread.ClientThread; /** * 这个类运行一下,是线程非安全 * 因为线程之间共享的static变量无法保证对于不同线程而言是安全的 * @author xujl * * 2017年6月2日 */ public class SequenceA implements Sequence { private static int number = 0; @Override public int getNumber() { number = number+1; return number; } public static void main(String[] args) { Sequence sequence = new SequenceA(); ClientThread ct1 = new ClientThread(sequence); ClientThread ct2 = new ClientThread(sequence); ClientThread ct3 = new ClientThread(sequence); ct1.start(); ct2.start(); ct3.start(); } }
线程安全和非安全用例
最新推荐文章于 2024-08-16 18:41:12 发布