两个线程交替打印奇数和偶数

public class ThreadTest {
    public static void main(String[] args) {
        Thread evenThread = new Thread(new PrintEven(),"打印奇数");
        Thread oddThread = new Thread(new PrintOdd(),"打印偶数");
        evenThread.start();
        oddThread.start();
    }
}

class Count{
    public static final Object lock = new Object();
}

class PrintEven implements Runnable{
    @Override
    public void run() {
        synchronized (Count.lock) {
            for(int i = 1; i < 10; i += 2) {
                System.out.println(Thread.currentThread().getName() + " : " + i);
                Count.lock.notifyAll();
                try {
                    Count.lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Count.lock.notifyAll();
        }
    }
}

class PrintOdd implements Runnable{
    @Override
    public void run() {
        synchronized (Count.lock) {
            for(int i = 2; i < 10; i += 2) {
                System.out.println(Thread.currentThread().getName() + " : " + i);
                Count.lock.notifyAll();
                try {
                    Count.lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Count.lock.notifyAll();
        }
    }
}

运行结果:

 

posted @ 2019-09-13 23:26  柯西丶不是你  阅读(530)  评论(0编辑  收藏  举报