使用Runnable實現資料共享

2022-09-29 12:00:09 字數 1697 閱讀 2452

使用runnable實現資料共享,供大家參考,具體內容如下

先上**:

public class testthread

public void run() buy one ticket, {} left. ", thread.currentthread().getname(), i);}}

}} @test

public void testrunable() throws interruptedexception

}樓上的**很簡單,模擬乙個售票系統。通過兩個thread物件開啟兩條執行緒同時執行乙個myrunnable程式設計客棧例項程式設計客棧。

幾個注意點:

1. 沒有加上synchronised關鍵詞的話,即

public void run() buy one ticket, {} left. ", thread.currentthread().getname(), i);}}

}系統的執行結果:

thread-1 buy one ticket, 8 left.

thread-2 buy one ticket, 8 left.

thread-2 buy one ticket, 6 left.

thread-1 buy one ticket, 6 left.

thread-2 buy one ticket, 5 left.

thread-1 buy one ticket, 4 left.

thread-2 buy one ticket, 3 left.

thread-1 buy one ticket, 2 left.

thread-2 buy one ticket, 1 left.

thread-1 buy one ticket, 0 left.

可以看到,缺少同步的程式輸出明顯有問題。

2. 在進入同步**塊之後,還需要對i的值再進行一次判斷,即,如果不加if判斷:

public void run() buy one ticket, {} left. ", thread.currentthread().getname(), i);}}

}程式的執行結果為:

thread-2 buy one ticket, 9 left.

thread-2 buy one ticket, 8 left.

thread-2 buy one ticket, 7 left.

thread-2 buy one ticket, 6 left.

thread-2 buy one ticket, 5 left.

thread-2 buy one ticket, 4 left.

thread-2 buy one ticket, 3 left.

thread-2 buy one ticket, 2 left.

thread-2 buy one ticket, 1 left.

thread-2 buy one ticket, 0 left.

thread-1 buy one ticket, -1 left.

可以看出,出現了「多賣」的現象, 所以需要在進入同步**塊中再進行一次if判斷。

總結 synchrowww.cppcns.comnised用於互斥訪問共享變數, 並在同步**塊中使用if判斷更新共享變數。

本文標題: 使用runnable實現資料共享

本文位址:

實現Runnable介面

實現runnable介面 宣告乙個實現runnable介面的類,然後實現run方法,分配類的例項,在建立thread時作為引數傳遞,並啟動 簡單說 1 實現runnable介面 2 重寫run方法 3 通過乙個thread物件 物件 呼叫start方法 建立執行緒方式二 1 建立 實現runnabl...

JAVA 實現Runnable介面

僅作為學習筆記 需求 實現乙個售票程式 建立執行緒的第二種方式 實現runnable介面 步驟 1,定義類實現runnable介面 2,覆蓋runnable介面中的run方法 將執行緒要執行的 存放在該run方法中 3,通過thread 類建立執行緒物件 4,將runnable介面的子類物件作為實際...

執行緒Thread與Runnable實現

當new 乙個thread的時候,就是在主線程的基礎上再開乙個子執行緒,cpu一會兒給主線程用,一會兒給子執行緒用,所以多執行緒會降低工作效率 1 thread 自己實現自己的run方法 public static voidmain string args throwsinterruptedexce...