下面是代碼的一部分。我很困惑爲什麼「通知1」不能真正喚醒正在等待的另一個功能。java多線程問題
它與接縫有關: 當一個線程正在爲一個對象執行一個同步方法時,所有其他線程調用同一對象的同步方法塊(暫停執行),直到第一個線程完成對象。
爲什麼結果不是: 等待, notify1, 等待完成, notify2, 。 。 。
取而代之的則是: 等待, notify1, notify2, notify2, 。 。 。 notify2, 通知2, 通知3, 等待光潔度, 跳過等待, 跳過等待, 跳過等待, 。 。 。
代碼 { 。 。 。
MultiThreadContent m;
void divideToParts(File testFile,FileInputStream fileInputStream, Object hashMachine) throws IOException, InterruptedException{
.
.
.
//run from here
m = new MultiThreadContent(fileInputStream,(int)temp23,(int) (testFile.length()%temp23), numberOfParts, hashMachine);
new Thread(new Read()).start();
m.update();
}
class Read implements Runnable{
@Override
public void run() {
try {
m.read();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class MultiThreadContent{
.
.
.
boolean preNotReady=true;
boolean updateNotFinished;
//read{
public synchronized void read() throws InterruptedException{
//initial{
readNextBlock();
preBlock=nextBlock;
read_notify();
System.out.println("notify 1");//d
if(finishedRead!=true)
{
readNextBlock();
read_wait();
}
else
return;
//}
while(finishedRead!=true){
preBlock=nextBlock;
read_notify();
System.out.println("notify 2");//d
readNextBlock();
read_wait();
}
//closing{
preBlock=nextBlock;
read_notify();
System.out.println("notify 3");//d
//}
}
void read_notify(){
preNotReady=false;
notifyAll();
}
void read_wait() throws InterruptedException{
if(updateNotFinished==true)
{
wait();
System.out.println("wait for update");//d
}
preNotReady=true;
}
//}
//update{
public synchronized void update() throws InterruptedException{
for (int i = 0; i < totalParts; i++) {
update_wait();
divideToParts_update(hashMachine, preBlock);
update_notify();
}
}
void update_notify(){
updateNotFinished=false;
notifyAll();
}
void update_wait() throws InterruptedException{
if(preNotReady){
System.out.println("wait");//d
wait();
System.out.println("wait finish");//d
}
updateNotFinished=true;
System.out.println("skip wait");//d
}
//}
}
}
'finishedRead'沒有定義?這是所有的代碼? – Kevin 2011-04-11 13:58:38
它是代碼的一部分。我很困惑爲什麼notifyAll不能真正喚醒正在等待「notify 1」的另一個函數。 – micahli123 2011-04-11 14:03:18