在面試菜鳥的時候碰到的鎖的編程問題,沒答好,記錄一下:
package com.xielu.test;
/**
* Hello world!
*
*/
public class App
{
private Object lock = new Object();
private static int cnt = 1;
private static final int MAX = 100;
public static void main( String[] args )
{
Thread th1 = new Thread(){
@Override
public void run(){
synchronized(lock){
while(cnt <= MAX){
if(cnt%2 != 0){
System.out.println(cnt);
cnt++;
lock.notifyAll();
} else{
try{
lock.wait();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
};
Thread th2 = new Thread(){
@Override
public void run(){
synchronized(lock){
while(cnt <= MAX){
if(cnt%2 == 0){
System.out.println(cnt);
cnt++;
lock.notifyAll();
} else{
try{
lock.wait();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
};
th1.start();
th2.start();
}
}
浙公網(wǎng)安備 33010602011771號