TestWaitAndNotify.java 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. public class TestWaitAndNotify {
  2. public static void main(String[] args) {
  3. WaitThread t1 = new WaitThread(1, 2, 50, false);
  4. WaitThread t2 = new WaitThread(2, 2, 50, false);
  5. t1.start();
  6. t2.start();
  7. }
  8. }
  9. class MyLock {}
  10. class WaitThread extends Thread {
  11. private static MyLock lock = new MyLock();
  12. private int init;
  13. private int delta;
  14. private int count;
  15. private boolean isLast;
  16. WaitThread(int init, int delta, int count, boolean isLast) {
  17. this.init = init;
  18. this.delta = delta;
  19. this.count = count;
  20. this.isLast = isLast;
  21. }
  22. @Override
  23. public void run() {
  24. for (int i = 0, num = init; i < count; i++) {
  25. System.out.println(num);
  26. num += delta;
  27. if (isLast && i == count - 1) return;
  28. synchronized (lock) {
  29. lock.notify();
  30. if (!isLast && i == count - 1) return;
  31. try {
  32. lock.wait();
  33. } catch (Exception e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. }
  38. }
  39. }