Java-多线程有序执行的方法

    同事无意间提出了这个问题,亲自实践了两种方法。当然肯定还会有更多更好的方法。如果你知道请麻烦留言告诉我。如果文中有不对的地方,也请告知,谢谢~

方法一

import java.util.concurrent.atomic.AtomicInteger;

public class OrderedThread1 {
	
	static AtomicInteger count = new AtomicInteger(0);

	public static void main(String[] args) throws InterruptedException {
		Task task1 = new Task(count, 0);
		Task task2 = new Task(count, 1);
		Task task3 = new Task(count, 2);
		Thread thread1 = new Thread(task1);
		Thread thread2 = new Thread(task2);
		Thread thread3 = new Thread(task3);
		thread1.setDaemon(true);
		thread2.setDaemon(true);
		thread3.setDaemon(true);
		thread1.start();
		thread2.start();
		thread3.start();
		
		Thread.sleep(1 * 1000);
	}

}

class Task implements Runnable {
	
	private AtomicInteger count;
	private int order;
	
	public Task(AtomicInteger count, int order) {
		this.count = count;
		this.order = order;
	}

	@Override
	public void run() {
		while (true) {
			if (count.get() % 3 == order) {
				System.out.println(Thread.currentThread().getName() + "  =====  "+ order);
				count.incrementAndGet();
			}
		}
	}
}

    这种方法应该是比较常见的解决方案。利用原子递增控制线程准入顺序。

方法二

public class OrderedThread2 {
	static Holder holder = new Holder();
	public static void main(String[] args) throws InterruptedException {
		
		Task1 task1 = new Task1(holder, 0);
		Task1 task2 = new Task1(holder, 1);
		Task1 task3 = new Task1(holder, 2);
		Thread thread1 = new Thread(task1);
		Thread thread2 = new Thread(task2);
		Thread thread3 = new Thread(task3);
		thread1.setDaemon(true);
		thread2.setDaemon(true);
		thread3.setDaemon(true);
		thread1.start();
		thread2.start();
		thread3.start();
		
		Thread.sleep(1 * 1000);
		

	}

}

class Task1 implements Runnable {
	
	Holder holder;
	int order;
	
	public Task1(Holder holder, int order) {
		this.holder = holder;
		this.order = order;
	}

	@Override
	public void run() {
		while (true) {
			if (holder.count % 3 == order) {
				System.out.println(Thread.currentThread().getName() + "  =====  "+ order);
				holder.count ++;
			}
		}
//		int i = 0;
//		while(i ++ < 10000){
//			holder.count ++;
//		}
	}
}
class Holder {
	volatile int count = 0;
}

    方法二使用了volatile关键字。让每个线程都能拿到最新的count的值,当其中一个线程执行++操作后,其他两个线程就会拿到最新的值,并检查是否符合准入条件。

ps:volatile不是线程安全的。而且两者没有任何关系。volatile变量不在用户线程保存副本,因此对所有线程都能提供最新的值。但试想,如果多个线程同时并发更新这个变量,其结果也是显而易见的,最后一次的更新会覆盖前面所有更新,导致线程不安全。在方法二中,一次只有一个线程满足准入条件,因此不存在对变量的并发更新。volatile的值是最新的与线程安全完全是不相干的,所以不要误用volatile实现并发控制。

转载于:https://my.oschina.net/u/2333484/blog/861067

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值