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行的双检查。

这个看似多线程资源争用的问题,竟然可以用无锁化来解决?究竟是为什么?我们下次讨论。

 posted on 2019-07-29 23:23  谷堆曲线  阅读(1672)  评论(0编辑  收藏  举报