演示代码:
package multithreading.Advanced; import java.util.concurrent.locks.ReentrantLock; // 测试Lock锁 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; // 定义Lock锁 private final ReentrantLock lock = new ReentrantLock(); @Override public void run() { while(true) { try { // 加锁 lock.lock(); if (ticketNums > 0){ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(ticketNums--); }else { break; } }finally { // 解锁 lock.unlock(); } } } }
运行结果: