Java中synchronized与java.util.concurrent.locks.Lock区别

相同点:Lock能完成synchronized所实现的所有功能

区别:Lock比synchronized更精确的线程语义和性能;chronized会自动释放锁,而Lock需要程序员手动释放,而且必须在finally从句中释放。Lock更强大的功能,如tryLock方法可以非阻塞方式去拿锁:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//synchronized
//java.util.concurrent.locks.Lock

public class ThreadTest {
	
	private class Adder implements Runnable{
		@Override
		public void run() {
			while(true){
				//1
//				synchronized (ThreadTest.this) {
//					System.out.println("j++=" + j++);
//				}
				//2
				lock.lock();
				try{
					System.out.println("j++=" + j++);
				}finally{
					lock.unlock();
				}
			}
		}	
	}	
	
	private class Subtractor implements Runnable{
		@Override
		public void run() {
			while(true){
				//1
//				synchronized(ThreadTest.this){
//					System.out.println("j--=" + j--);
//				}
				//2
				lock.lock();
				try{
					System.out.println("j--=" + j--);
				}finally{
					lock.unlock();
				}
			}
		}		
	}
	
	private int j;
	private Lock lock = new ReentrantLock();
	
	public static void main(String[] args) {
		ThreadTest tt = new ThreadTest();
		for(int i=0; i<2; i++){
			new Thread(tt.new Adder()).start();
			new Thread(tt.new Subtractor()).start();
		}
	}
}
程序运行结果:

Java中synchronized与java.util.concurrent.locks.Lock区别_第1张图片






你可能感兴趣的:(java,线程)