1. 程式人生 > >ThreadLocal實現執行緒安全的經典例子

ThreadLocal實現執行緒安全的經典例子

public class SequenceNumber {


	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SequenceNumber sn = new SequenceNumber();
		TestClient t1 = new TestClient(sn);
		TestClient t2 = new TestClient(sn);
		TestClient t3 = new TestClient(sn);
		t1.start();
		t2.start();
		t3.start();
		
	}
	private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>(){
		@Override
		protected Integer initialValue() {
			// TODO Auto-generated method stub
			return 0;
		}
	};
	public int getNextNum(){
		seqNum.set(seqNum.get()+1);
		return seqNum.get();
		
	}
	private static class TestClient extends Thread{
		private SequenceNumber sn;
		public TestClient(SequenceNumber sn){
			this.sn = sn;
		}
		public void  run(){
			for(int i=0;i<3;i++){
				System.out.println("thread["+Thread.currentThread().getName()+"]sn["+sn.getNextNum()+"]");
			}
		}
		
	}


}