Sharing a Scanner between two threads
<p>How can I share Scanner object between two threads so that I can pass value to Standard i/p stream in one thread and display in another thread?</p>

<p>I have created two threads as below:</p>

<p>In <strong>Thread1</strong> I used below code:</p>

<pre><code>while(true)
{

//Thread.currentThread().sleep(5000); // if I used this it is printing ABCD
str = System1Class.scan.nextLine();
System.out.println(str);
}
</code></pre>

<p>In <strong>Thread2</strong> I use the code below:</p>

<pre><code>String st = "ABCD";
InputStream is = new ByteArrayInputStream(st.getBytes());
System.setIn(is);
ThreadMainClass.scan  = new Scanner(System.in); // here I am trying to refresh the     global object "scan"
</code></pre>

<p>Here the 'scan' object is created globally in the class ThreadMainClass as:</p>

<pre><code>public static Scanner scan = new Scanner(System.in);
</code></pre>

<p>It is accessing by both threads. My requirement is: I want to display "ABCD" in Thread1 which is passing from Thread2. It is displaying If I put some delay so that Scanner object will be created before the line in Thread1:</p>

<pre><code>str = System1Class.scan.nextLine();
</code></pre>

<p>But I don not want two use any delay. So is there any way that I can do? I want to display "ABCD" at that instant when it is passed from Thread2. Also in the meantime Thread1 should wait data from the console i.e. Thread1 should not wait for any notification from Thread2. If data is passed from Thread2 just get it and print it otherwise it should wait from console only.  </p>

<p>I think I need a way to REFRESH the 'scan' object from Thread2 but I am not sure. :)</p>

<p>Thanks in advance </p>
