Note that there are some explanatory texts on larger screens.

plurals
  1. POThread Deadlock
    text
    copied!<p>I have 2 threads. One thread prints odd numbers and the second thread prints even numbers. Now, I have to execute the threads alternatively so that i can output 1,2,3,4,5,6,.....</p> <p>I have written a program for this and this is resulting in a deadlock. Can someone explain what is the problem with the code and how to rectify it?</p> <pre><code>class BooleanObject { boolean flag; BooleanObject(boolean flag) { this.flag = flag; } } class EvenThread extends Thread { Object lock; BooleanObject flagObj; EvenThread(Object o, BooleanObject flag) { lock = o; this.flagObj = flag; } public void run() { for (int i=2;i&lt;100;i+=2) { synchronized(lock) { if (flagObj.flag == false) { flagObj.flag = true; lock.notify(); } else { try { while (flagObj.flag == true) { lock.wait(); } } catch (InterruptedException e) { } } System.out.println(i); } } } } class OddThread extends Thread { Object lock; BooleanObject flagObj; OddThread(Object o, BooleanObject flag) { lock = o; this.flagObj = flag; } public void run() { for (int i=1;i&lt;100;i+=2) { synchronized(lock) { if (flagObj.flag == true) { flagObj.flag = false; lock.notify(); } else { try { while(flagObj.flag == false) { lock.wait(); } } catch (InterruptedException e) { } } System.out.println(i); } } } } public class EvenOddThreads { public static void main(String[] args) { Object obj = new Object(); BooleanObject flagObj = new BooleanObject(true); EvenThread et = new EvenThread(obj,flagObj); OddThread ot = new OddThread(obj,flagObj); et.setName("even thread"); ot.setName("odd thread"); et.start(); ot.start(); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload