Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to make two threads wait and notify each other
    primarykey
    data
    text
    <p>I have to create two Threads which have to poll and object from a queue in 2 seconds intervals. </p> <p>The first Thread poll and object then wait and notify the second one to poll the object from it's queue.</p> <p>I read all about wait and notify but nothing works with me.</p> <p>Any sugestions?</p> <p>First thread:</p> <pre><code>public class SouthThread extends Thread { private Queue&lt;Car&gt; q = new LinkedList&lt;Car&gt;(); public void CreateQueue() { Scanner input = new Scanner(System.in); for (int i = 0; i &lt; 2; i++) { Car c = new Car(); System.out.println("Enter registration number: "); String regNum = input.nextLine(); c.setRegNum(regNum); q.offer(c); } } public int getQueueSize() { return q.size(); } @Override public void run() { while (q.size() != 0) try { while (q.size() != 0) { synchronized (this) { System.out.print("The car with registration number: "); System.out.print(q.poll().getRegNum()); System.out .println(" have passed the bridge from the south side."); this.wait(2000); notify(); } } } catch (InterruptedException e) { e.printStackTrace(); } } </code></pre> <p>}</p> <p>Second thread:</p> <pre><code>public class NorthThread extends Thread { private Queue&lt;Car&gt; q = new LinkedList&lt;Car&gt;(); public void CreateQueue() { Scanner input = new Scanner(System.in); for (int i = 0; i &lt; 2; i++) { Car c = new Car(); System.out.println("Enter registration number: "); String regNum = input.nextLine(); c.setRegNum(regNum); q.offer(c); } } public int getQueueSize() { return q.size(); } @Override public void run() { try { while (q.size() != 0) { synchronized (this) { System.out.print("The car with registration number: "); System.out.print(q.poll().getRegNum()); System.out .println(" have passed the bridge from the north side."); this.wait(2000); notify(); } } } catch (InterruptedException e) { e.printStackTrace(); } } </code></pre> <p>}</p> <p>Main Thread:</p> <pre><code>public class Main { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub SouthThread tSouthThread = new SouthThread(); NorthThread tNorthThread = new NorthThread(); tSouthThread.CreateQueue(); tNorthThread.CreateQueue(); System.out.println(tSouthThread.getQueueSize()); tSouthThread.start(); tNorthThread.start(); } </code></pre> <p>}</p>
    singulars
    1. This table or related slice is empty.
    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