Java multithreading 06_ReentrantLock

Java multithreading 06_ReentrantLock


public class TestLock {
    
    
	public static void main(String[] args) {
    
    
		TestLock2 testLock2 = new TestLock2();
		new Thread(testLock2).start();
		new Thread(testLock2).start();
		new Thread(testLock2).start();

	}
}

class TestLock2 implements Runnable {
    
    

	int ticketNums = 10;

	@Override
	public void run() {
    
    
		while (true) {
    
    
			if (ticketNums > 0) {
    
    
				try {
    
    
					Thread.sleep(1000);
				} catch (InterruptedException e) {
    
    
					e.printStackTrace();
				}
				System.out.println(ticketNums--);
			} else {
    
    
				break;
			}

		}
	}

}
10
9
9
8
7
8
6
5
4
3
1
2
import java.util.concurrent.locks.ReentrantLock;
 
public class TestLock {
    
    
	public static void main(String[] args) {
    
    
		TestLock2 testLock2 = new TestLock2();
		new Thread(testLock2).start();
		new Thread(testLock2).start();
		new Thread(testLock2).start();
		
	}
}

class TestLock2 implements Runnable{
    
    

	int ticketNums = 10;
	
	private final ReentrantLock lock = new ReentrantLock();
	
	@Override
	public void run() {
    
    
		while(true) {
    
    
			lock.lock();
			try {
    
    
				if(ticketNums>0) {
    
    
					try {
    
    
						Thread.sleep(1000);
					} catch (InterruptedException e) {
    
    
						e.printStackTrace();
					}
					System.out.println(ticketNums--);
				}else {
    
    
					break;
				}
			}  finally {
    
    
				lock.unlock();
					
		}
	}
	
}
10
9
8
7
6
5
4
3
2
1

The comparison of synchronized and Lock:

Lock是显示锁(手动开启和关闭锁,别忘记关闭锁)
synchronized 是隐式锁,出了作用域自动释放

Lock只有代码块锁
 synchronized有代码块锁和方法锁

使用 Lock 锁,JVM 将花费较少时间来调度线程,性能更好,并且具有更好的扩展性(提供更多的子类,比如 ReentrantLock)

Guess you like

Origin blog.csdn.net/BLU_111/article/details/108393551
Recommended