3個線程打印從0打印到100,要求打印出來是有序的,線程也是按順序執行。看起來很簡單的一個面試題,事實上想寫的好還是有難度的。
public class Main {
public volatile static int n = 0;
public static final int LIMIT = 100;
public static final int THREAD_COUNT = 3;
public static class ARunnable implements Runnable {
int mode;
public ARunnable(int mode){
this.mode = mode;
}
@Override
public void run(){
while(n <= LIMIT){
if (n % THREAD_COUNT == mode && n <= LIMIT) {
System.out.println(n);
n++;
} else {
Thread.yield();
}
}
}
}
public static void main(String[] arg){
new Thread(new ARunnable(0)).start();
new Thread(new ARunnable(1)).start();
new Thread(new ARunnable(2)).start();
}
}
注意第20行的雙檢查。
這個看似多線程資源爭用的問題,竟然可以用無鎖化來解決?究竟是為什么?我們下次討論。
