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 42 43 44 45 46 47 48 49
| import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.Random;
public class MyRunnable implements Runnable{ private int ticket = 30; private Random rand = new Random(); private Lock lock = new ReentrantLock(); public MyRunnable() { System.out.println("This class starts with " + this.ticket + " tickets."); } @Override public void run() { while (this.ticket > 0) { if (lock.tryLock()){ try { System.out.println(Thread.currentThread().getName() + " acquired lock."); this.ticket--; System.out.println(Thread.currentThread().getName() + " sold a ticket, now has " + this.ticket + " tickets."); } catch (Exception e) { System.err.println(e); } finally { System.out.println(Thread.currentThread().getName() + " released lock."); lock.unlock(); } int nxt = rand.nextInt(20) * 10; try { Thread.sleep(nxt); } catch (InterruptedException e) { e.printStackTrace(); } } else { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } System.out.println("Now, " + Thread.currentThread().getName() + " has ended."); } }
|