在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(); } } } } } } }
在这个示例中,我们创建了两个线程:oddThread
和evenThread
。oddThread
负责打印奇数,evenThread
负责打印偶数。它们共享一个锁对象lock
和一个静态变量count
。
当count
为奇数时,oddThread
获取锁并打印数字,然后增加count
并调用lock.notify()
唤醒等待的线程。接着,oddThread
调用lock.wait()
释放锁并进入等待状态。
当count
为偶数时,evenThread
的行为与oddThread
类似。
这样,两个线程就可以交替打印奇偶数了。