TestWaitAndNotify.java 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. public class TestWaitAndNotify {
  2. public static void main(String[] args) {
  3. WaitThread t1 = new WaitThread("t1", 1, 2, 50, false);
  4. WaitThread t2 = new WaitThread("t2", 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 String name;
  13. private int init;
  14. private int delta;
  15. private int count;
  16. private boolean isLast;
  17. WaitThread(String name, int init, int delta, int count, boolean isLast) {
  18. this.name = name;
  19. this.init = init;
  20. this.delta = delta;
  21. this.count = count;
  22. this.isLast = isLast;
  23. }
  24. @Override
  25. public void run() {
  26. for (int i = 0, num = init; i < count; i++) {
  27. System.out.println(name + ": " + num);
  28. num += delta;
  29. if (isLast && i == count - 1) return;
  30. synchronized (lock) {
  31. lock.notify();
  32. if (!isLast && i == count - 1) return;
  33. try {
  34. lock.wait();
  35. } catch (Exception e) {
  36. e.printStackTrace();
  37. }
  38. }
  39. }
  40. }
  41. }