12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- public class TestWaitAndNotify {
- public static void main(String[] args) {
- WaitThread t1 = new WaitThread(1, 2, 50, false);
- WaitThread t2 = new WaitThread(2, 2, 50, false);
- t1.start();
- t2.start();
- }
- }
- class MyLock {}
- class WaitThread extends Thread {
- private static MyLock lock = new MyLock();
- private int init;
- private int delta;
- private int count;
- private boolean isLast;
- WaitThread(int init, int delta, int count, boolean isLast) {
- this.init = init;
- this.delta = delta;
- this.count = count;
- this.isLast = isLast;
- }
- @Override
- public void run() {
- for (int i = 0, num = init; i < count; i++) {
- System.out.println(num);
- num += delta;
- if (isLast && i == count - 1) return;
- synchronized (lock) {
- lock.notify();
- if (!isLast && i == count - 1) return;
- try {
- lock.wait();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
|