執行緒的基本方法

2022-04-14 16:11:32 字數 3206 閱讀 6176

程序:資源分配的基本單位

執行緒:資源排程的基本單位

為了程序能進行併發操作

建立程序有兩種方法(一般推薦第二種,因為單繼承問題)

先來看看執行緒的建構函式

2.1 繼承thread類,重寫run()

public class threadtest extends thread 

//重寫方法

public void run() }

public static void main(string args)

}

2.2 實現runnable介面,重寫run()

public class runnabletest implements runnable 	}	

public static void main(string args)

}

// 上面兩種方法都是執行緒交替進行

執行緒1:::0

執行緒1:::1

執行緒1:::2

執行緒1:::3

執行緒1:::4

執行緒2:::0

執行緒1:::5

執行緒1:::6

執行緒1:::7

執行緒1:::8

執行緒1:::9

執行緒1:::10

執行緒2:::1

3.1 命名 getname()

/**

* allocates a new object. this constructor has the same

* effect as

* , where is a newly generated

* name. automatically generated names are of the form

* n, where n is an integer.

*/public thread()

/* for autonumbering anonymous threads. */

private static int threadinitnumber;

private static synchronized int nextthreadnum()

thread thread = new thread(() -> );

thread.setname("新執行緒名");

新執行緒名
3.1 守護執行緒(setdaemon)

public final void setdaemon(boolean on) 

daemon = on; //設定守護執行緒為真

}/* whether or not the thread is a daemon thread. */

// private boolean daemon = false;

3.2 優先順序(setpriority)

// max_priority 最大級別10

// min_priority 最小0

// norm_priority 普通5

public final void setpriority(int newpriority)

if((g = getthreadgroup()) != null)

setpriority0(priority = newpriority); //設定級別,後面遇到native方法不說明了}}

public static void main(string args)
執行緒1:::97

執行緒1:::98

執行緒1:::99

執行緒2:::3

執行緒2:::4

執行緒2:::5

在前面例項中呼叫該函式,發現t1執行緒cpu執行時間片多於t2執行緒,t1完成了t2還在開頭3.3 sleep

public class threadtest extends thread 

//重寫方法

public void run()

}public static void main(string args) throws interruptedexception

}

執行緒2--96

執行緒2--97

執行緒2--98

執行緒2--99

//10秒後,main執行緒睡眠

*****==

3.4 join

public class threadtest extends thread 

//重寫方法

public void run()

}public static void main(string args) throws interruptedexception

}

3.5 wait和notify

thread.wait();

thread.notify();

3.6 yield

使當前執行緒從執行狀態轉為就緒狀態,即可能讓別的執行緒執行,也可能自己再次執行

3.7 interrupt

thread t1 = new thread(new runnable(()->

// 中斷的處理**……

dosomething();

}).start();

#### 3.8 exit

退出當前執行緒(或者當run方法結束也是執行緒結束)

3.9 start和run區別

3.10 currentthread()

獲取當先執行的執行緒,thread thread = thread.currentthread(),屬於靜態方法

執行緒 基本方法

執行緒相關的基本方法有 wait,notify,notifyall,sleep,join,yield 等。執行緒等待 wait 呼叫該方法的執行緒進入 waiting 狀態,只有等待另外執行緒的通知或被中斷才會返回,需要注意的 是呼叫 wait 方法後,會釋放物件的鎖。因此,wait 方法一般用在同...

執行緒基本方法

執行緒相關的基本方法有wait,notify,notifyall,sleep,join,yield 等。執行緒等待 wait sleep 導致當前執行緒休眠,與 wait 方法不同的是 sleep 不會釋放當前占有的鎖,sleep long 會導致 執行緒進入timed wating狀態,而wait...

執行緒狀態及基本方法

虛擬機器實際呼叫的方法 設定該執行緒為守護執行緒,守護執行緒是一種特殊的執行緒,主要是為其他執行緒提供服務.被守護的執行緒一旦銷毀,那麼守護執行緒也沒有存在的必要了.示例1 innerthread設定為thread的守護執行緒,模擬心跳傳送.如果連線中斷,則心跳中斷.public class dea...