1.暫停執行緒呼叫thread.sleep()方法會使當前程序立即暫停,進入休眠狀態,即是暫時將某執行緒停止執行
// 暫停執行緒
static
void
method()
執行", thread.currentthread.name)
; console.
writeline
("將暫停3秒鐘"
, thread.currentthread.name)
; thread.
sleep
(3000);
console.
writeline
("工作結束"
, thread.currentthread.name);}
static
void
main
(string
args)
開始啟動"
, thread.currentthread.name)
;thread mythread =
newthread
(new
threadstart
(method));
mythread.name =
"子執行緒"
; mythread.
start()
; console.
writeline
("將暫停2秒鐘"
, thread.currentthread.name)
; thread.
sleep
(2000);
console.
writeline
("工作結束"
, thread.currentthread.name)
; console.
read()
;}
2.中斷執行緒
主線程中,呼叫執行緒例項名。interrupt(),將會中斷正在等待的執行緒例項,同時也會引發threadinterruptedexception異常,如果此執行緒當前未阻塞在等待、休眠或連線狀態中,則下次開始阻塞時它將被中斷。
//中斷執行緒
static
public
void
method()
開始執行"
,thread.currentthread.name)
;try
暫停",thread.currentthread.name)
;//infinite用於指定無期限等待一段時間,執行緒處理方法接受乙個常量引數int
thread.
sleep
(timeout.infinite);}
catch
(threadinterruptedexception ex)
被中斷"
+ex.message, thread.currentthread.name);}
}static
void
main
(string
args)
開始執行"
, thread.currentthread.name)
;thread thread =
newthread
(new
threadstart
(method));
thread.name =
"subthread"
; thread.
start()
; thread.
interrupt()
; thread.
join()
; console.
writeline
("結束執行"
, thread.currentthread.name)
; console.
read()
;}
多執行緒 執行緒中中斷執行緒的方法
public class threaddemo13 catch interruptedexception e system.out.println 交易終止 t1.start thread.sleep 2000 system.out.println 有內鬼終止交易 flag true public ...
多執行緒學習(一) 中斷執行緒
執行緒的中斷 第一種方法 stop方法 不正確的終止方法,已經被jdk棄用,原因是可能會出現執行緒安全問題。示例 public class stopthread extends thread catch exception e j public void print public static vo...
中斷執行緒 interrupt
呼叫interrupt 通知執行緒應該中斷 1 如果執行緒處於阻塞狀態,則執行緒立即退出被阻塞狀態,並丟擲乙個interruptedexception異常 2 如果執行緒處於正常活動狀態,那 package com.mall.controllor.alene import sun.managemen...