Java - 多線程 - 創建線程

進程:   本質上是正在運行中的程序。

線程:   是進程中一個負責程序執行的控制單元(執行路徑)。一個進程至少會有一個線程


一個進程有多個執行路徑稱之爲多線程。開啓多個線程是爲了同時運行多部分代碼。

每一個線程都有自己運行的內容,這些內容就是線程要執行的任務。

多線程決解了多部分代碼同時運行的問題,但是太多的線程同時運行會導致程序的效率降低。


Java的多線程系統兼容單核和多核兩種操作系統:

|--    在單核系統中 併發執行的線程 共享CPU,每一個線程得到一片CPU時間週期,所以在單核系統中多個線程不是真在同時運行的。

|--    在多核的系統中,多個線程有可能被同步執行。程序的效率更高,操作速度更快。


Java 的 Thread 類:

|--    Java的多線程系統基於Thread 類,它封裝了線程的執行。Thread  類的實例就是線程的代理。


Java主線程:

Java程序啓動時,開始運行的線程,稱爲主線程。

|--   其他的子線程都是從主線程產生的

|--   通常,主線程是最後結束執行的線程,因爲他要關閉各種動作。

|--   主線程默認是main,5,main

/**分析下面代碼**/

class CurrentThreadDemo 
{
	public static void main(String[] args) 
	{
		Thread t = Thread.currentThread();//返回當前線程的引用
		System.out.println("當前正在運行的線程是" + t);//當前正在運行的線程是Thread[main,5,main]
		t.setName("abc");
		System.out.println("把線程名稱改成" + t);//把線程名稱改成Thread[abc,5,main]
		try{//因爲sleep()可能拋出InterruptedException異常所以要被監視
			for(int i=0;i<=5;i++){
				System.out.println(i);
				t.sleep(100);//在指定的毫秒數內讓當前正在執行的線程休眠(暫停執行)
			}
		}catch(InterruptedException e){			
			System.out.println("當前線程被中斷");
		}
	}
}
/**[main,5,main]分別表示線程的名稱、優先級、線程所屬線程組的名稱**/


Java創建線程的兩種方法:

|--   第一種方式:   實現 Runnable 接口

/*
新建一個子線程和主線程一起運行

    主線程要實現的任務打印6-10
    通過實現 Runnable 接口的 run() 封裝子線程要實現的任務
    子線程要實現的任務是打印1-5
    我們希望在任務對象創建的時候就開始一個新的線程
    那麼就要在構造函數中創建新的 Thread 對象。並運行線程。

*/

class NewThread implements Runnable
{
	private Thread t;
	NewThread(){
		t = new Thread(this);
		System.out.println("新建一個子線程:"+t);
		t.start();
	}
	public void run(){//新進程要實現的任務
		try{
			for(int i=1;i<=5;i++){
				System.out.println(i +"---"+ t.getName());
				t.sleep(100);
			}
		}catch(InterruptedException e){
			System.out.println("子線程被中斷");
		}
		System.out.println(t.getName() + "子線程退出");
	}
}
class ThreadDemo
{
	public static void main(String[] args) 
	{
		new NewThread();
		new NewThread();
		Thread t = Thread.currentThread();
		try{
			for(int i=6;i<=10;i++){
				System.out.println(i);
				t.sleep(100);
			}
		}catch(InterruptedException e){
			System.out.println("主線程被中斷");
		}
		System.out.println("主線程退出");
	}
}

|--   第二種方式:    擴展 Thread 類

/**

通過繼承 Thread 類創建子線程

**/

class NewThread extends Thread
{
	NewThread(){
		super("pan");
		System.out.println("新建一個子線程:"+this);
	}
	public void run(){//新進程要實現的任務
		try{
			for(int i=1;i<=5;i++){
				System.out.println(i +"---"+ this.getName());
				sleep(100);//繼承Thread就擁有了它裏面的方法,可以直接使用
			}
		}catch(InterruptedException e){
			System.out.println("子線程被中斷");
		}
		System.out.println(this.getName() + "子線程退出");
	}
}
class ThreadDemo
{
	public static void main(String[] args) 
	{
		NewThread n = new NewThread();
		n.start();
		Thread t = Thread.currentThread();
		try{
			for(int i=6;i<=10;i++){
				System.out.println(i);
				t.sleep(200);
			}
		}catch(InterruptedException e){
			System.out.println("主線程被中斷");
		}
		System.out.println("主線程退出");
	}
}

如果不重寫 Thread 的其他方法,創建線程的最好方法是實現Runnable接口,通過實現Runnable接口不需要繼承Thread 可以自由的繼承其他類。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章