Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can use inter thread communication using <code>wait</code> and <code>notify</code> like this :</p> <pre><code>class ReadNum { int arr[]; private volatile int counter = 0; public ReadNum() { counter = 0 ; } public ReadNum(int size) { arr = new int[size]; for (int i = 0; i &lt; size ; i++) { arr[i] = i; } } public void setArray(int[] arr) { counter = 0; this.arr = arr; } public synchronized void readOdd() { while (counter &lt; arr.length) { if (counter % 2 != 0) { System.out.println(Thread.currentThread().getName()+":-&gt;"+arr[counter]); counter++; } notify(); try{ wait(); }catch(Exception ex){ex.printStackTrace();} } notify();//So that other EvenThread does'nt hang if OddThread completes earlier } public synchronized void readEven() { while (counter &lt; arr.length) { if (counter % 2 == 0) { System.out.println(Thread.currentThread().getName()+":-&gt;"+arr[counter]); counter++; } notify(); try{ wait(); }catch(Exception ex){ex.printStackTrace();} } notify();//So that other OddThread does'nt hang if EvenThread completes earlier } } public class SequenceRead { public static void main(String st[]) { final ReadNum rn = new ReadNum(); int arr[]= {1,2,34,78,99,45,4545,987,343,45}; rn.setArray(arr); Thread th1 = new Thread(new Runnable() { @Override public void run() { rn.readEven(); } },"EvenReadThread"); Thread th2 = new Thread( new Runnable() { @Override public void run() { rn.readOdd(); } },"OddReadThread"); th2.start();th1.start(); } } </code></pre> <p><strong>UPDATE</strong><br></p> <p>Here is the explanation that you asked for about Race Condition.</p> <blockquote> <p><strong>Race Condition</strong> : <em>"It is a situation where multiple threads can access same resource (typically object's instance variables) and can produce corrupted data if one thread "races in" or "sneaks in" too quickly before an operation that should be atomic has completed. Hence the output of program is unpredictable because it is dependent on the sequence or timing of starting, execution and completion of the various threads accessing the same resource ."</em></p> </blockquote> <p>For example consider the code given below:</p> <pre><code>class Race { private int counter; public void printCounter() { while(counter &lt; 100) { try { Thread.sleep(10);//Added to show Race Effect. } catch (Exception ex){} counter = counter + 1; } System.out.println(Thread.currentThread().getName() +" : "+counter);//If we don't consider Race condition then the Output should be 100 for all threads. } } public class MainClasss { public static void main(String st[]) { final Race race = new Race(); Thread[] th = new Thread[2]; //Creating 2 threads to call printCounter of object race for (int i = 0 ; i &lt; th.length ; i++) { th[i] = new Thread( new Runnable() { public void run() { race.printCounter(); } }, "Thread"+i); } //Starting all Threads for (Thread thr : th ) { thr.start(); } } } </code></pre> <p>And here is the output that that I am getting , It might vary on your system.</p> <pre><code>Thread1 : 100 Thread0 : 101 </code></pre> <p>All threads are not printing 100 as expected!!! <strong>Why</strong> ? Because Program has no control on when an executing Thread will be preempted by another thread.It all depends upon JVM Thread Scheduler.<br>One of the possible explanations for above output is as follows:</p> <blockquote> <ol> <li>At counter = 99 , Thread1 sneaked inside the while loop and slept for 10 ms . </li> <li>JVM Scheduler now preempted Thread1 by Thread0 .</li> <li>Thread1 goes inside "while" loop because it finds counter &lt; 100</li> <li>At Thread.sleep Thread0 is preempted by Thread1.</li> <li>Thread1 increases the counter by 1.</li> <li>Thread1 prints the counter value as 100 and finishes.</li> <li>Thread0 continues execution and increases the counter by 1 and makes counter = 101</li> <li>Thread0 prints the counter value as 101 and finishes.</li> </ol> </blockquote> <p>This is the live exhibition of Race Condition.<br> To Avoid this Race condition you should make the <code>ReadNum</code> method as synchronized , So that when a Thread enters that method , it takes the monitor and become owner of the synchronized method . And that thread is preempted only after it completes the all operation <strong>Atomically</strong> . I hope it gave you a good overview of Race Condition now.</p>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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