1. 程式人生 > >Java多執行緒24:使執行緒具有有序性

Java多執行緒24:使執行緒具有有序性

正常的情況下,執行緒的執行時多個執行緒之間執行任務的時機是無序的。可以通過改造程式碼的方式使他們執行具有有序性。 程式碼如下:

package unit7;

public class Demo10_Run {
	
	public static void main(String[] args) {
		Object lock = new Object();
		Demo10_MyThread a = new Demo10_MyThread(lock, "A", 1);
		Demo10_MyThread b = new Demo10_MyThread(lock, "B", 2);
		Demo10_MyThread c = new Demo10_MyThread(lock, "C", 0);
		a.start();
		b.start();
		c.start();
	}
	
}

class Demo10_MyThread extends Thread {
	
	private Object lock;
	private String showChar;
	private int showNumPosition;
	private int printCount = 0;//統計列印了幾個字母
	volatile private static int addNumber = 1;
	public Demo10_MyThread(Object lock, String showChar, int showNumPosition) {
		super();
		this.lock = lock;
		this.showChar = showChar;
		this.showNumPosition = showNumPosition;
	}
	
	public void run() {
		try {
			synchronized (lock) {
				while (true) {
					if (addNumber % 3 == showNumPosition) {
						System.out.println("ThreadName="
								+ Thread.currentThread().getName() + " runCount=" + addNumber + " " + showChar);
						lock.notifyAll();
						addNumber++;
						printCount++;
						
						if (printCount == 3) {
							break;
						}
					} else {
						lock.wait();
					}
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

執行結果如下: 在這裡插入圖片描述