Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This could be an exercise on threads and lock monitors, but there is nothing to do in parallel that give you advantages.</p> <p>In your code when a thread 1 (OddThread or EvenThread) ends his work and prints out "Odd Thread Finish" (or "Even Thread Finish") the other thread 2 is waiting a notify() or a notifyAll() that never will happen because the first is over.</p> <p>You have to change EvenThread and OddThread adding a synchronized block with a notify call on commShare just after the while cycle. I removed the second if-branch because in this way you don't continue to check the while condition but get a wait on commShare soon.</p> <pre><code>class EvenThread implements Runnable { private Share commShare; private int number = 2; public EvenThread(Share obj) { this.commShare = obj; } public void run() { System.out.println("Even Thread start"); while (number &lt;= 50) { synchronized (commShare) { if (commShare.flag) { System.out.println("Even Thread:" + number); number += 2; commShare.flag = false; } commShare.notify(); try { commShare.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } synchronized (commShare) { commShare.notify(); System.out.println("Even Thread Finish"); } } } class OddThread implements Runnable { private int number = 1; private Share commShare; public OddThread(Share obj) { this.commShare = obj; } public void run() { System.out.println("Odd Thread start"); while (number &lt;= 50) { synchronized (commShare) { if (!commShare.flag) { System.out.println("Odd Thread: " + number); number += 2; commShare.flag = true; } commShare.notify(); try { commShare.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } synchronized (commShare) { commShare.notify(); System.out.println("Odd Thread Finish"); } } </code></pre> <p>Finally, in the main you have to join for each thread you started. It's sure that Thread.currentThread() returns just one of yours threads? We have started two threads and those threads we should join.</p> <pre><code>try { even.join(); odd.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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