Note that there are some explanatory texts on larger screens.

plurals
  1. POReading an array consecutively with two threads
    primarykey
    data
    text
    <p>I have an array : int[] arr = {5,4,3,1,2};</p> <pre><code> I want to do like this:: 5 should be read by thread one 4 should be read by thread two 3 should be read by thread one 1 should be read by thread two 2 should be read by thread one </code></pre> <p>I have tried my best this simple program:</p> <pre><code>package com.techighost.create.deadlock; public class ArrayReading implements Runnable { volatile int index = 0; int[] arr; public ArrayReading(int[] arr) { this.arr = arr; } @Override public void run() { synchronized (arr) { for (;index&lt;=(arr.length-1);) { if (index % 2 == 0 &amp;&amp; Thread.currentThread().getName().equals("Thread-One")) { System.out.println(arr[index] + " " + Thread.currentThread().getName()); index++; arr.notify(); } else if (index % 2 != 0 &amp;&amp; Thread.currentThread().getName().equals("Thread-Two")) { System.out.println(arr[index] + " " + Thread.currentThread().getName()); index++; arr.notify(); }else{ System.out.println("In else " + Thread.currentThread().getName()); try { arr.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } public static void main(String[] args) throws InterruptedException { int[] arr = { 5, 4, 3, 1, 2 }; ArrayReading arrayReading = new ArrayReading(arr); Thread t = new Thread(arrayReading); t.setName("Thread-One"); Thread t1 = new Thread(arrayReading); t1.setName("Thread-Two"); t.start(); t1.start(); t.join(); t1.join(); } } </code></pre> <p><strong>I think that this thread name check should not be there? Any body please suggest what can be done to remove this check</strong></p>
    singulars
    1. This table or related slice is empty.
    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.
    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