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() {
try {
while (true){
if (ticketNums>0){
try {
lock.lock();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("还剩下"+ticketNums--+"张票");
}else {
break;
}
}
}finally {
lock.unlock();
}
}
}
Lock锁实现线程安全的案例
最新推荐文章于 2023-10-14 20:02:37 发布