Java-多線程有序執行的方法

    同事無心間提出了這個問題,親自實踐了兩種方法。固然確定還會有更多更好的方法。若是你知道請麻煩留言告訴我。若是文中有不對的地方,也請告知,謝謝~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實現併發控制。ide

相關文章
相關標籤/搜索