package com.Java;标签:testLock2,TestLock2,synchronized,Thread,lock,start,Lock,new,锁能 From: https://www.cnblogs.com/fc666/p/17189319.html
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 extends Thread {
int stickNum = 100;
private ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
lock.lock(); //锁住
if (stickNum > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();//释放锁
}
System.out.println(stickNum--);
}
}
}
}