首页 > 编程语言 > 详细

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

时间:2019-07-30 03:02:09      阅读:173      评论:0      收藏:0      [点我收藏+]

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

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

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

原文:https://www.cnblogs.com/caoshenglu/p/11267195.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!