TestAwaitAndSignal.java 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import java.util.concurrent.locks.*;
  2. public class TestAwaitAndSignal {
  3. public static void main(String[] args) {
  4. Lock lock = new ReentrantLock();
  5. Condition c1 = lock.newCondition();
  6. Condition c2 = lock.newCondition();
  7. Condition c3 = lock.newCondition();
  8. AwaitThread t1 = new AwaitThread(lock, c1, c2, 1, 3, 50, true);
  9. AwaitThread t2 = new AwaitThread(lock, c2, c3, 2, 3, 50, false);
  10. AwaitThread t3 = new AwaitThread(lock, c3, c1, 3, 3, 50, false);
  11. t1.start();
  12. t2.start();
  13. t3.start();
  14. try {
  15. Thread.sleep(60);
  16. lock.lock();
  17. c1.signal();
  18. } catch (Exception e) {
  19. e.printStackTrace();
  20. } finally {
  21. lock.unlock();
  22. }
  23. }
  24. }
  25. class AwaitThread extends Thread {
  26. Lock lock;
  27. Condition curr;
  28. Condition next;
  29. int init;
  30. int delta;
  31. int count;
  32. boolean first;
  33. AwaitThread(Lock lock, Condition curr, Condition next, int init, int delta, int count, boolean first) {
  34. this.lock = lock;
  35. this.curr = curr;
  36. this.next = next;
  37. this.init = init;
  38. this.delta = delta;
  39. this.count = count;
  40. this.first = first;
  41. }
  42. @Override
  43. public void run() {
  44. System.out.println("Thread " + init + " is running.");
  45. for (int i = 0, num = init; i < count; i++) {
  46. lock.lock();
  47. try {
  48. curr.await();
  49. System.out.println(num);
  50. num += delta;
  51. Thread.sleep(5);
  52. next.signal();
  53. } catch (Exception e) {
  54. e.printStackTrace();
  55. } finally {
  56. lock.unlock();
  57. }
  58. }
  59. }
  60. }