如何多線程有序打印0到100


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行的雙檢查。

這個看似多線程資源爭用的問題,竟然可以用無鎖化來解決?究竟是為什么?我們下次討論。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM