執行緒之同步通訊

2021-06-09 03:42:27 字數 1460 閱讀 6154

執行緒之同步通訊

所謂執行緒之同步通訊,為了避免死鎖,讓執行緒在進入堵塞狀態時盡量釋放其鎖定的資源,以為其他的執行緒提供執行的機會;

執行緒間的通訊:

兩個或兩個以上的執行緒處理同乙個資源,處理的動作是不一樣的。

這樣就需要將不同的動作**放到不同的run

方法中,

run方法要封裝到單獨的類中。

同步中使用:

wait():讓當前執行緒處於等待狀態,釋放

cpu資源,同時釋放鎖。

notify():喚醒等待的執行緒,喚醒第乙個

notifyall():喚醒所以等待的執行緒。

//資源類

class res catch (interruptedexception e) else catch (interruptedexception e) 

}class

res1 

catch

(interruptedexception e)  }

this

.name

=name;

this

.***

=***; b

=true;

notify(); }

public

synchronized

void

out() 

catch

(interruptedexception e)  }

system.

out.println(

name

+"......"

+***);

b=false;

notify(); }

}class

input1 

implements

runnable

@override

public

void

run() 

else

s=(s+1)%2; }

} }

class

output1 

implements

runnable

@override

public

void

run() 

} }

這兩個執行出來的結果是一樣的,不過我比較喜歡第二種,可能是更具體,更簡單,不像第一種那麼複雜,把同步封裝在資源裡,然後底下直接呼叫即可;

wait()

:被鎖定的物件可以呼叫wait()

方法,這將導致當前執行緒被阻塞並釋放該物件的互斥鎖,即解除了

wait()

方法當前物件的鎖定狀態,其他的執行緒就有機會訪問該物件。

notify():

喚醒呼叫wait()

方法後被阻塞的執行緒。每次執行該方法只能喚醒乙個執行緒。

notifyall()

:喚醒所有呼叫wait()

方法被阻塞的執行緒。

執行緒之同步通訊

執行緒之同步通訊 所謂執行緒之同步通訊,為了避免死鎖,讓執行緒在進入堵塞狀態時盡量釋放其鎖定的資源,以為其他的執行緒提供執行的機會 執行緒間的通訊 兩個或兩個以上的執行緒處理同乙個資源,處理的動作是不一樣的。這樣就需要將不同的動作 放到不同的run方法中,run方法要封裝到單獨的類中。同步中使用 w...

多執行緒之執行緒同步

pulse lockobj 表示釋放當前被lock的lockobj,容許其他執行緒呼叫。相當於暫時掛起當前執行緒 wait lockobj 表示等待當前被其他執行緒占用的lockobj。下面的 將會交替執行兩個執行緒 class ticktock console.write tick monitor...

執行緒同步通訊

package itcast.thread public class traditionalthreadcommunication start for int i 1 i 50 i public class business catch interruptedexception e for int ...