sleep():方法使用时注意
在你使用锁的时候,最好在锁的里面进行等待,如果在锁的外面等待,会造成多个线程同时得到锁,然后同时解锁。如果用于抢票之类的话,可能会造成轮询状态。
代码如下:
public class TestLock {
public static void main(String[] args) {
Test test=new Test();
new Thread(test,"老王").start();
new Thread(test,"小王").start();
new Thread(test,"王老爷子").start();
}
}
class Test implements Runnable{
private final Lock lock=new ReentrantLock(); //可重入锁
private boolean flag=true;
private int votes=20;
@Override
public void run() {
while (flag){
try {
Thread.sleep(1000);//这样会造成三个线程同时得到锁。然后同时解锁
lock.lock();//加锁
if (votes>0){
System.out.println(Thread.currentThread().getName()+"拿到了"+votes--+"票");
}else {
flag=false;
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();//解锁
}
}
}
}
希望童鞋们注意。