如何实现两个线程交替打印1-100之内的奇偶数?
public class Main{
public static int number = 100;
public static void main(String[] args) {
Object obj = new Object();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
while(number > 0){
synchronized (obj){
if(number % 2 == 0){
System.out.println("thread="+Thread.currentThread().getName() + " " +number--);
obj.notifyAll();
}else {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
while(number > 0){
synchronized (obj){
if(number % 2 == 1){
System.out.println("thread="+Thread.currentThread().getName() + " " + number--);
obj.notifyAll();
}else {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}