1. 程式人生 > >Java 多執行緒同時執行

Java 多執行緒同時執行

    我們建立三個任務與三個執行緒,讓三個執行緒啟動,同時執行三個任務。

    任務類必須實現 Runable 介面,而 Runable 介面只包含一個 run 方法。需要實現

這個方法來告訴系統執行緒將如何執行。

    建立任務:

    TaskClass task = new TaskClass(...);

    任務必須線上程中執行,建立執行緒:

    Thread thread = new Thread(task);

    然後呼叫 start 方法告訴 Java 虛擬機器該執行緒準備執行,如下:

    thread.start();

    下面的程式建立三個任務和三個執行這些任務的執行緒:

任務1 列印字母 a 10次

任務2 列印字母 b 10次

任務3 列印 1 ~ 10  的整數

執行這個程式,則三個執行緒共享CPU,在控制檯上輪流列印字母和數字。

程式碼:

public class TaskDemo {

	public static void main(String[] args) {
		//建立三個任務
		Runnable printA = new PrintChar('a', 10);
		Runnable printB = new PrintChar('b', 10);
		Runnable print100 = new PrintNum(10);
		//建立三個執行緒
		Thread thread1 = new Thread(printA);
		Thread thread2 = new Thread(printB);
		Thread thread3 = new Thread(print100);
		//啟動三個執行緒,將同時執行建立的三個任務
		thread1.start();
		thread2.start();
		thread3.start();
	}
}
//此任務將一個字元列印指定次數
class PrintChar implements Runnable {

	private char charToPrint;
	private int times;
	//建構函式
	public PrintChar(char charToPrint, int times) {
		this.charToPrint = charToPrint;
		this.times = times;
	}
	//重寫介面Runable中的run方法,告訴系統此任務的內容
	@Override
	public void run() {
		for (int i = 0; i < times; i++) {
			System.out.print(charToPrint);
		}
	}
}
//此任務列印1~n
class PrintNum implements Runnable {
	private int lastNum;
	
	public PrintNum(int lastNum) {
		this.lastNum = lastNum;
	}

	@Override
	public void run() {
		for (int i = 0; i < lastNum; i++) {
			System.out.print(" " + i);
		}
	}
}

結果:

注意:每次執行的結果都不相同,因為我們並不知道三個任務的執行順序。