Java 多線程之Thread類繼承

Thread類中最重要的方法是run(),run()是屬於那些會與程序中其他線程“併發”或“同時”執行的代碼。

線程並不是按照它們創建時的順序執行的。事實,CPU處理一個現有線程集的順序是不確定的,除非我們使用Thread中的setPriority()方法調整它們的優先級。

public class SimpleThread extends Thread{
	private int countDown = 5;
	private int threadNumber;
	private static int threadCount = 0;
	public SimpleThread(){
		threadNumber = ++threadCount;
		System.out.println("Making " + threadNumber);
	}
	public void run(){
		while(true){
			System.out.println("Thread " + threadNumber + "(" + countDown + ")");
			if(--countDown == 0) return;
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		for(int i = 0; i < 5; i++)
			new SimpleThread().start();
	System.out.println("All Thread Started");
	}
}

上面這個例子中SimpleThread繼承了Thread類,並覆蓋了run()方法,每通過一次循環,計數就減一,計數爲0時進程中止。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章