一道面试题,多线程, 一个线程增加变量,另一个打印出变量值。我的做法:
public class MultiThreadsTest {
int size = 1000;
private int i= 0;
boolean printlable = false;
Object lock = new Object();
Thread addI = new Thread(new Runnable(){
public void run(){
for(int j=0; j<size; j++){
synchronized(lock){
if(printlable){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
synchronized(lock){
i++;
printlable = true;
lock.notify();
}
}
}
});
Thread printI = new Thread(new Runnable(){
public void run(){
for(int j=0; j<size; j++){
synchronized(lock){
if(!printlable){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
synchronized(lock){
System.out.println(i);
printlable = false;
lock.notify();
}
}
}
});
public static void main(String[] args){
MultiThreadsTest mt = new MultiThreadsTest();
mt.addI.start();
mt.printI.start();
}
}