今天想起前段時(shí)間的一道面試編程題,要求兩個(gè)線程實(shí)現(xiàn)打印奇偶數(shù)寓盗,當(dāng)時(shí)因?yàn)闆]能很好的理解wait和notify灌砖。所以代碼有問題。今天又查了下贞让,重新試了下周崭,先上正確結(jié)果:
偶數(shù)線程
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();
}
}
}
}
}
}
奇數(shù)線程
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();
}
}
}
}
}
}
主函數(shù)
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代碼塊中续镇,否則會(huì)報(bào)IllegalMonitorStateException異常。