温馨提示×

java多线程交替打印奇偶数怎么实现

小亿
110
2024-09-03 10:37:45
栏目: 编程语言

在Java中,可以使用synchronized关键字和wait()notify()方法来实现多线程交替打印奇偶数。下面是一个简单的示例:

public class AlternatePrinting {

    private static final Object lock = new Object();
    private static int count = 1;

    public static void main(String[] args) {
        Thread oddThread = new Thread(new OddNumberPrinter(), "OddThread");
        Thread evenThread = new Thread(new EvenNumberPrinter(), "EvenThread");

        oddThread.start();
        evenThread.start();
    }

    static class OddNumberPrinter implements Runnable {
        @Override
        public void run() {
            while (count <= 100) {
                synchronized (lock) {
                    if (count % 2 == 1) {
                        System.out.println(Thread.currentThread().getName() + ": " + count++);
                        lock.notify();
                    } else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    static class EvenNumberPrinter implements Runnable {
        @Override
        public void run() {
            while (count <= 100) {
                synchronized (lock) {
                    if (count % 2 == 0) {
                        System.out.println(Thread.currentThread().getName() + ": " + count++);
                        lock.notify();
                    } else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}

在这个示例中,我们创建了两个线程:oddThreadevenThreadoddThread负责打印奇数,evenThread负责打印偶数。它们共享一个锁对象lock和一个静态变量count

count为奇数时,oddThread获取锁并打印数字,然后增加count并调用lock.notify()唤醒等待的线程。接着,oddThread调用lock.wait()释放锁并进入等待状态。

count为偶数时,evenThread的行为与oddThread类似。

这样,两个线程就可以交替打印奇偶数了。

0