今天想起前段时间的一道面试编程题,要求两个线程实现打印奇偶数,当时因为没能很好的理解wait和notify。所以代码有问题。今天又查了下,重新试了下,先上正确结果:
偶数线程
public static class Thread1 extends Thread {
Object lock;
public Thread1(Object lock) {
this.lock = lock;
}
@Override
public void run() {
super.run();
synchronized (lock) {
while (true && i < 100) {
if (i % 2 == 0) {
System.out.println("--Thread1-->" + i);
i++;
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
奇数线程
public static class Thread2 extends Thread {
Object lock;
public Thread2(Object lock) {
this.lock = lock;
}
@Override
public void run() {
super.run();
synchronized (lock) {
while (true && i < 100) {
if (i % 2 == 1) {
System.out.println("--Thread2-->" + i);
i++;
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
主函数
public static void main(String[] args) {
Object lock = new Object();
Thread t1 = new Thread1(lock);
Thread t2 = new Thread2(lock);
t1.start();
t2.start();
}
可以简单理解成lock.notify()是唤醒别人,lock.wait()是休眠自己。
而且要注意放在synchronized代码块中,否则会报IllegalMonitorStateException异常。