Why does this get into a deadlock immediately on start - it prints a line and then freezes(after the edits advised)?
This is probably because the firstthread misses the notify trigger before it starts waiting.
What is the resolution?
public class threadTwo{
AtomicInteger i=new AtomicInteger(0);
Boolean b=new Boolean(false);
class firstThread implements Runnable{
AtomicInteger i;
Boolean b;
firstThread(AtomicInteger i,Boolean b){
this.i=i;
this.b=b;
}
public void run(){
while(true){
synchronized(i){
try{
while(b==false)
i.wait();
if(i.intValue()<30){
i.incrementAndGet();
System.out.println( Thread.currentThread().getId() + " - " + i.intValue());
}
b=false;
i.notify();
}catch(InterruptedException x){}
}
}
}
}
class secondThread implements Runnable{
AtomicInteger i;
Boolean b;
secondThread(AtomicInteger i,Boolean b){
this.i=i;
this.b=b;
}
public void run(){
while(true){
synchronized(i){
try{
while(b==true)
i.wait();
if(i.intValue()<40){
i.getAndAdd(2);
System.out.println( Thread.currentThread().getId() + " - " + i.intValue());
}
b=true;
i.notify();
}catch(InterruptedException x){}
}
}
}
}
void runThread(){
Thread t1 = new Thread(new firstThread(i,b));
Thread t2 = new Thread(new secondThread(i,b));
t1.start();
t2.start();
try{
t1.join();
t2.join();
}catch(Exception e){}
System.out.println("Result : " + i.intValue());
}
public static void main(String[] args){
new threadTwo().runThread();
}
}