外部執行緒停止Java子執行緒的方法

2021-09-07 15:51:38 字數 984 閱讀 9519

一、thread.stop()

官方不推薦,because it is inherently unsafe.

二、方式一

1. 執行緒類示例

public

class

threadt1 implements runnable

public

void

stop()

public

void

run()

system.

out.println("

stopped!!!");

}}

2. 使用示例

threadt1 th1 = new

threadt1();

th1.start();

//新建執行緒並啟動

th1.stop(); //

停止這個執行緒

三、方式二

1. 執行緒類示例

public

class

threadt2 extends thread

public

void

run()

system.

out.println("

stopped!!!");

}}

2.使用示例

threadt2 th2 = new

threadt2();

th2.start();

//新建執行緒並啟動

th2.stopbymark(); //

停止這個執行緒

附、關於thread.interrupt()

通過這個方式也能停止執行緒。

前提條件:

public

void

run()

catch (interruptedexception e)

}

Java停止執行緒

1 run方法正常結束 public class stopthreaddemo class printthread extends thread 2 可以在run方法中設定標記讓執行緒正常結束 public class stopthreaddemo class printthread extends...

執行緒的sleep yield join 停止方法

1 執行緒休眠 sleep long time 單位為毫秒 執行緒休眠指的是讓執行緒暫緩執行以一下,等到了預計時間之後再恢復執行 sleep方法會讓當前執行緒立即交出cpu,但不會釋放物件鎖,即使當前持有某個物件的的執行緒呼叫sleep方法休眠了,其他執行緒也無法持有該物件 public class...

Java多執行緒3 停止執行緒

關於執行緒的停止,主要有兩種,一種是自然停止,即執行緒體正常執行完畢。還有一種則是外部干涉,我們主要講的是外部干涉。其實也比較簡單 外部干涉 1 執行緒類中定義執行緒體使用的標識,如boolean型 2 執行緒體中使用該標識 3 提供對外的方法改變該標識 4 外部根據條件呼叫該標識 我們還是用例子來...