【发布时间】:2011-04-11 13:55:28
【问题描述】:
以下是部分代码。我很困惑为什么“通知 1”不能真正唤醒另一个正在等待的函数。
接缝与以下内容有关: 当一个线程正在为一个对象执行同步方法时,所有其他为同一对象调用同步方法的线程都会阻塞(暂停执行),直到第一个线程处理完该对象。
为什么结果不是: 等待, 通知1, 等完结 通知2, . . .
而是: 等待, 通知1, 通知2, 通知2, . . . 通知2, 通知 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没有定义?这是所有的代码吗? -
它是代码的一部分。我很困惑为什么 notifyAll 不能真正唤醒在“通知 1”处等待的另一个函数。
标签: java multithreading