I can not understand why no thread never enters into the method wait
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();
}
}
In my code as I can prevent the problem of starvation caused by the simulation method of writing with sleep ? Because if a thread is put to sleep for a long time always will never write than one that you put to sleep for a short time