两个线程交替打印奇偶数 交替打印奇偶数是面试中常见的文件,这里主要使用了wait/notify来实现,你还有什么好的方法吗
public static void main(String[] args) {
int i = 0;
Thread a1 = new Thread(new MyThread(i));
Thread a2 = new Thread(new MyThread1(i));
a1.start();
a2.start();
}
static class MyThread implements Runnable{
private int i;
public MyThread(int num){
this.i = num;
}
@Override
public void run() {
synchronized (Object.class) {
while(true) {
i++;
if (i % 2 != 0) {
System.out.println(i);
try {
Object.class.notifyAll();
Object.class.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
static class MyThread1 implements Runnable{
private int i;
public MyThread1(int num){
this.i = num;
}
@Override
public void run() {
synchronized (Object.class) {
while(true) {
i++;
if (i % 2 == 0) {
System.out.println(i);
try {
Object.class.notify();
Object.class.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}