代码如下:
package practice1;
public class JiOuOne {
private static volatile int num = 0;
private static final int max = 100;
public static void main(String[] args) {
String monitor = "monitor";
Thread oddThread = new Thread(new OddNumber(monitor));
oddThread.setName("偶数打印:");
Thread evenThread = new Thread(new EvenNumber(monitor));
evenThread.setName("奇数打印:");
oddThread.start();
evenThread.start();
}
static class OddNumber implements Runnable {
private String monitor;
public OddNumber(String monitor) {
this.monitor = monitor;
}
@Override
public void run() {
while (num <= max) {
synchronized (monitor) {
while (num % 2 != 0) {
try {
monitor.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "->" + num);
num++;
monitor.notify();
}
}
}
}
static class EvenNumber implements Runnable {
private String monitor;
public EvenNumber(String monitor) {
this.monitor = monitor;
}
@Override
public void run() {
while (num < max) {
synchronized (monitor) {
while (num % 2 == 0) {
try {
monitor.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "->" + num);
num++;
monitor.notify();
}
}
}
}
}
运行结果:
