關於Java執行緒通訊(初級)

2021-08-02 13:48:49 字數 1313 閱讀 2622

該demo模仿插入和取出棧頂的資料

變數的宣告

private

int top = -1; // 棧頂

private

int mdata = new

int[1024];// 儲存資料的陣列

private

boolean isalive = false; // 此時棧頂是否有資料

取出棧頂資料

當執行查詢操作時檢視標誌位(棧頂是否有資料)

假設結果為true那麼取出資料並重置標誌位,否則wait。

public

intpop() catch (interruptedexception e)

}system.out.println("被喚起-->pop");

isalive = false;// 設定標誌位為false

int i = mdata[top--];

notifyall();// 喚醒此時正在等待壓入資料的執行緒

return i;

}}

向棧頂插入資料

當執行查詢操作時檢視標誌位(棧頂是否有資料)

假設結果為false那麼插入資料並重置標誌位,否則wait。

public

void

push(int i) catch (interruptedexception e)

}system.out.println("壓入資料-->push");

mdata[++top] = i;

isalive = true;// 設定標誌位為true

notifyall();// 喚醒此時正在等待取出棧頂資料的現成

}}

測試類長這樣

public

class

test

};thread.start();

thread thread2 = new thread() catch (interruptedexception e)

stack.push(1);}};

thread2.start();

}}

執行結果

拿到物件鎖

-->pop

釋放物件鎖

-->pop

拿到物件鎖

-->push

壓入資料

-->push

被喚起-

->pop

1

流程如下

java執行緒通訊

題目 子執行緒迴圈10次,接著主線程迴圈100,接著又回到子執行緒迴圈10次,接著再回到主線程又迴圈100,如此迴圈50次。public class traditionalthreadcommunicationtest start for int i 1 i 50 i static class bu...

Java 執行緒通訊

sychronized關鍵字 對方法使用該關鍵字,可以保證每次只有乙個執行緒獲取monitor的許可權,從而確保執行緒對共享資源操作的不會出現異常 wait wait 方法屬於object,有三個過載方法,該方法必須在sychronized方法或同步 塊中呼叫,呼叫該方法的執行緒會進入wait 對應...

Java執行緒通訊

假設現在系統中有兩個執行緒,分別代表取錢和存錢,現在假設系統有一種特殊的要求,系統要求存款者和取款者不斷重複訪問款,而且要求每當存款者將錢存入指定賬戶時,取錢者就立即取出該筆錢,不允許連續存款兩次,也不允許連續取款兩次 public class threadconnection class acco...