首页 > 编程语言 > 详细

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

时间:2019-09-13 23:39:28      阅读:156      评论:0      收藏:0      [点我收藏+]
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();
        }
    }
}

 

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

原文:https://www.cnblogs.com/trnanks/p/11517954.html

(1)
(1)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!