我有點困惑這個任務對我有螺紋:我有三大類:Java線程:同步的價值讀寫同一個對象
- 存儲整數的類,我們稱之爲
StoredInteger
- 一個Thread類(
IncrementThread
)是應該遞增StoredInteger
類的整數值 - 另一個線程類(
ReadThread
)是應該讀取來自StredInteger
類 整數值
的方法,所述方法應該去輸出應被同步,例如:
IncementThread
值1寫入StoredInteger
ReadThread
讀取值1從StoredInteger
IncementThread
寫入值2到StoredInteger
ReadThread
從StoredInteger
讀取值...等等
我遇到的問題是,ReadThread等待IncrementThread完成,然後它只讀取最後一個值。以下是我的一些代碼:
public class ReadThread extends Thread {
private StoredInteger stored_integer;
...
@Override
public void run()
{
int i = 0;
while(i < 100)
{
synchronized(this.getStoredInteger())
{
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
...
}
System.out.format("%s: Reading %d from StoredInteger\n", this.getClass().getSimpleName(), this.getStoredInteger().getValue());
i++;
}
}
}
...
}
。
public class IncrementThread extends Thread {
private StoredInteger stored_integer;
...
@Override
public void run()
{
int i = 0;
while(i < 100)
{
synchronized(this.getStoredInteger())
{
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
...
}
System.out.format("%s: Writing %d to StoredInteger\n", this.getClass().getSimpleName(), i);
this.getStoredInteger().setValue(i);
i++;
}
}
}
...
}
而且運行的線程:
public static void main(String[] args) throws InterruptedException
{
StoredInteger intgr = new StoredInteger();
Thread write = new Thread(new IncrementThread(intgr));
Thread read = new Thread(new ReadThread(intgr));
write.start();
read.start();
write.join();
read.join();
}
我在做什麼錯在這裏?
謝謝!
這是問題!謝謝你的努力:) – Comforse
用2個信號燈更容易 – Dimitri
確實!我只是更習慣於監視器:P – BlueMoon93