码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-09-14 00:11:56      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:str   art   pre   style   interrupt   count   线程   bsp   into   

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();
        }
    }
}

 

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

标签:str   art   pre   style   interrupt   count   线程   bsp   into   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!