main.class
public class Solution1006 {
public static void main(String[] args) {
MyObject my = new MyObject();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0; i<10; i++)
my.printOdd();
}
},"奇数线程").start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0; i<10; i++)
my.printEven();
}
},"偶数线程").start();
}
}
MyObject.class
public class MyObject {
private static int num = 1;
public synchronized void printOdd(){
while(num%2 == 0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + ": " + num);
num++;
this.notifyAll();
}
public synchronized void printEven(){
while(num%2 != 0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + ": " + num);
num++;
this.notifyAll();
}
}
结果: