【发布时间】:2014-11-24 20:50:18
【问题描述】:
我不明白为什么没有线程永远不会进入方法等待
public class File {
private boolean writing = false;
public synchronized void write()
{
String name = Thread.currentThread().getName();
while(this.writing == true){
System.out.println(name +" wait ");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.writing=true;
System.out.println(name +" writing ");
try{
Thread.sleep((int)(Math.random()*3000));
} catch( InterruptedException e){
e.printStackTrace();
}
this.writing=false;
System.out.println(name +" writing end ");
this.notifyAll();
}
}
public class M_thread extends Thread{
File file;
public M_thread(String name,File f){
super(name);
this.file=f;
}
public void run(){
while(true){
file.write();
}
}
}
public class Main {
public static void main(String[] args) {
File file=new File();
new M_thread("t1",file).start();
new M_thread("t2",file).start();
new M_thread("t3",file).start();
}
}
在我的代码中,我可以防止由 sleep 编写的模拟方法引起的饥饿问题吗?因为如果一个线程被长时间休眠,永远不会写比你让一个短时间休眠的线程
【问题讨论】:
-
我错了,你应该把真与假交换,但这只是一个逻辑错误代码 java 应该更正
-
请编辑您的问题以反映这一点。
-
是的,当然..我已经添加了。
-
离题:
File不是一个类的最佳名称,因为它与一个非常常用的内置类 (java.io.File) 冲突。 -
如果我没看错的话,“同步”包装器会为您“等待”(字面上将线程排队),所以当每个线程获得执行 writer() 函数的上下文时,再次写入等于false。
标签: java