1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| public class Testlock { public static void main(String[] args) { Testlock02 testlock02 = new Testlock02();
new Thread(testlock02).start(); new Thread(testlock02).start(); new Thread(testlock02).start(); }
}
class Testlock02 implements Runnable{
int tickNum = 10;
private final ReentrantLock lock = new ReentrantLock();
@Override public void run() { while(true){ try { lock.lock(); if(tickNum > 0){ Thread.sleep(1000); System.out.println(Thread.currentThread().getName() + "拿到了第" + tickNum-- + "张票"); } else { break; } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } }
|