java中使用ReentrantLock实现线程安全
作者:互联网
如下代码:
class Window4 implements Runnable { private int ticket=100;
//1、先定义一个变量 private ReentrantLock rlock=new ReentrantLock(true); @Override public void run() { while (true){ try {
//2、加锁 rlock.lock(); if(ticket>0){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+":"+ticket); ticket--; }else{ break; } } finally {
//3、锁释放
rlock.unlock();
} } } }
代码中有注释。
标签:java,Thread,ReentrantLock,private,线程,rlock,ticket,100 来源: https://www.cnblogs.com/puzi0315/p/16138342.html