執行緒喚醒的兩種方式

2021-10-19 18:36:12 字數 1106 閱讀 1694

通過 locksupport.park(); 阻塞的執行緒,可以通過下面兩種方式喚醒:

通過 locksupport.unpark(thread) 喚醒

使用中斷 thread.interrupt() 喚醒

public

static

void

main

(string[

] args)

,開始執行!"

+current.

getname()

);for(;;

)...."

+current.

getname()

);locksupport.

park()

; system.out.

println

("當前執行緒{}已經被喚醒...."

+current.

getname()

);}}

,"t0");

t0.start()

;try

執行緒!"

+t0.

getname()

);locksupport.

unpark

(t0)

; thread.

sleep

(2000);

t0.interrupt()

;}catch

(interruptedexception e)

}

執行結果:

,開始執行!t0

準備park住當前執行緒:..

..t0

準備喚醒執行緒!t0

當前執行緒已經被喚醒...

.t0準備park住當前執行緒:..

..t0

當前執行緒已經被喚醒...

.t0準備park住當前執行緒:..

..t0

當前執行緒已經被喚醒...

.t0準備park住當前執行緒:..

..t0

當前執行緒已經被喚醒...

.t0準備park住當前執行緒:..

..t0 ..

.

執行緒建立的兩種方式

建立執行緒的兩種方式 1.繼承thread並重寫方法,在run方法中定義執行緒要執行的任務 class mythread extends thread public class threaddemo1 2.實現runable介面並重寫run方法 class myrunnable implements...

執行緒的兩種定義方式

執行緒的兩種定義方式 1,繼承thread類 1 定義執行緒 寫乙個類,繼承thread類,重寫run 方法。package com.hqyj.demo1 public class thread1 extends thread 2 啟動執行緒 直接new這個類,呼叫這個類的start的方法 pack...

建立執行緒的兩種方式

thread thread new thread catch interruptedexception e system.out.println thread.currentthread getname system.out.println this.getname thread.start thr...