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

Posted 柯西丶不是你

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了两个线程交替打印奇数和偶数相关的知识,希望对你有一定的参考价值。

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

 

以上是关于两个线程交替打印奇数和偶数的主要内容,如果未能解决你的问题,请参考以下文章

交替打印出奇数和偶数

面试题:用程序实现两个线程交替打印 0~100 的奇偶数

线程交替运行

Java两个线程实现交替运行-以交替打印奇偶数为例

面试常考:C#用两个线程交替打印1-100的五种方法

经典笔试题:两个线程交替打印奇偶数