package com.lyon.demo; 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 tickerNums = 10; //定义lock锁 --可重入锁 private final ReentrantLock lock =new ReentrantLock(); @Override public void run() { while (true){ lock.lock();//加锁 try{ if(tickerNums>0){ // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } System.out.println(Thread.currentThread().getName()+" "+tickerNums--); }else{ break; } }finally { //解锁 lock.unlock(); } } } }
多线程之可重入锁
最新推荐文章于 2021-12-11 16:57:53 发布