Synchronized和ThreadLocal的区别

关于理论知识,以下这两个文章讲的很好:


Spring单例与线程安全小结

ThreadLocal的原理和在框架中的应用

不多说,上代码,自己运行一下就知道区别了

package com.spri.test;

public class SequenceNumber {
	
	public Object obj = new Object();
	// ①通过匿名内部类覆盖ThreadLocal的initialValue()方法,指定初始值
	private static ThreadLocal seqNum = new ThreadLocal() {
		public Integer initialValue() {
			return 0;
		}
	};
	
	public int getCount(){
		synchronized(obj){
			return count++;
		}
		
	}
	public int getAno(){
		ano++;
		return ano;
	}
	public int ano = 0;
	public int count =0;
	//②获取下一个序列值
	public int getNextNum() {
		seqNum.set(seqNum.get() + 1);
		return seqNum.get();
	}

	public static void main(String[] args) {
		SequenceNumber sn = new SequenceNumber();
		//③3个线程共享sn,各自产生序列号
		TestClient t1 = new TestClient(sn);
		TestClient t2 = new TestClient(sn);
		TestClient t3 = new TestClient(sn);
		t1.start();
		t2.start();
		t3.start();
	}

	private static class TestClient extends Thread {
		
		private int num = 0;
		private SequenceNumber sn;

		public TestClient(SequenceNumber sn) {
			this.sn = sn;
		}

		public void run() {
			for (int i = 0; i < 3; i++) {// ④每个线程打出3个序列值
				System.out.println("thread[" + Thread.currentThread().getName() + "] sn[" + sn.getNextNum() + "]");
				System.out.println(sn.getCount());
				System.out.println(sn.getAno());
			}
		}
	}
}


结果:


thread[Thread-0] sn[1]
thread[Thread-2] sn[1]
1
1
thread[Thread-1] sn[1]
2
2
thread[Thread-2] sn[2]
3
3
0
4
thread[Thread-2] sn[3]
4
5
thread[Thread-1] sn[2]
5
6
thread[Thread-0] sn[2]
6
7
thread[Thread-1] sn[3]
7
8
thread[Thread-0] sn[3]
8
9

readLocal不是为了解决并发同步用的,是为了隔离变量用的。同步是为了让多个线程共同操作一个对象而不乱掉,而ThreadLocal直接就把某个对象在各自线程中重新实例化一个了,各个线程都有自己的该对象,所以就不用管同步不同步了

你可能感兴趣的:(线程安全)