Note that there are some explanatory texts on larger screens.

plurals
  1. POJava Threads Synchronizing Problem
    primarykey
    data
    text
    <p>I have the following 2 classes code that produce this result for instance:</p> <pre><code>Wainting for calculation to complete... Calculator thread says HELLO! T1 says that total is 10 Wainting for calculation to complete... Wainting for calculation to complete... </code></pre> <p>Now threads are waiting but nobody is going to notify them. How can I force the threads from T1 to T3 to run before the "Calculator thread" wake em up?</p> <pre><code>public class Calculator implements Runnable{ private int total; public int getTotal() { return total; } @Override public void run() { synchronized (this) { for (int i = 0; i &lt; 5; i++) { total += i; } System.out.println(Thread.currentThread().getName() + " says HELLO!"); notifyAll(); } } } import static java.lang.System.out; public class Reader implements Runnable{ private Calculator c; public Reader(Calculator calc) { c = calc; } public Calculator getCalculator() { return c; } public static void main(String[] args) { Calculator calc = new Calculator(); Reader read = new Reader(calc); Thread thread1 = new Thread(read); Thread thread2 = new Thread(read); Thread thread3 = new Thread(read); thread1.setName("T1"); thread2.setName("T2"); thread3.setName("T3"); thread1.start(); thread2.start(); thread3.start(); Thread calcThread = new Thread(read.getCalculator()); calcThread.setName("Calculator thread"); calcThread.start(); } } @Override public void run() { synchronized (c) { try { out.println("Wainting for calculation to complete..."); c.wait(); } catch (InterruptedException e) { e.printStackTrace(); } out.println(Thread.currentThread().getName() + " says that " + "total is " + c.getTotal()); } } } </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.
 

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