What I am trying to achieve is, creating 2 threads sharing a common static boolean resource so that depending on the flag values the first thread should exit, but still the first thread runs.
This is the code below,
class SharedResource08{
public synchronized void doIt() throws Exception{
while(!SharedResource07.getBFlag()){
System.out.println(" THE THREAD "+Thread.currentThread().getName());
Thread.sleep(250);
}
}
}
class SharedResource07{
private static boolean bFLag = false;
public static synchronized void setBFlag(boolean bFLag){
bFLag = bFLag;
System.out.println(" THREAD "+Thread.currentThread().getName()+" setting value bFLag := "+bFLag);
}
public static boolean getBFlag(){
return bFLag;
}
}
class MyThread07 extends Thread{
private SharedResource08 resource;
MyThread07(String threadName,SharedResource08 resource){
super(threadName);
this.resource = resource;
}
public void run(){
try{
if(getName().equals("JACK")){
resource.doIt();
}else if(getName().equals("JILL")){
SharedResource07.setBFlag(true);
}
}catch(Exception e){
System.out.println(e);
}
}
}
public class Ex07{
public static void main(String[] args){
SharedResource08 resource = new SharedResource08();
MyThread07 t1 = new MyThread07("JACK",resource);
MyThread07 t2 = new MyThread07("JILL",resource);
t1.start();
t2.start();
}
}
What I am expecting is, thread t1 will execute the doit() method of class SharedResource08,
in the meantime the second thread t2 should set the flag bFLag of class SharedResource07 to true, now once this flag is true, the thread t1 should exit the method doIt(),
but this doesn’t happen, my thread t1 goes on printing the SOP.
Need some suggestion.
Just a typical mistake:
Change this:
for this:
Some IDEs are good at avoiding this kind of errors by signaling warnings on code. Always keep an Eclipse at hand 🙂