线程交替打印奇偶

class TestThread implements Runnable {
private int i = 1;

    public void run() {
        while (true) {
            synchronized (this) {
                notify();
                System.out.println(Thread.currentThread().getName() + ":" + i++);
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (i == 101) {
                    notify();//线程2执行完输出100后,进行等待池,线程1被唤醒拿到锁从wait()后面开始执行,此时i=101,需要先把线程2从等待池唤醒再结束循环
                    break;
                }
            }
        }
    }
}

public class Test7 {
    public static void main(String[] args) {
        TestThread t = new TestThread();
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);

        t1.setName("线程1");
        t2.setName("线程2");

        t1.start();
        //把线程2延迟一会开启,为了始终让线程1先拿到锁
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.start();
    }
}

猜你喜欢

转载自www.cnblogs.com/mdc1771344/p/10063878.html