access System.in / out several threads
Hi,
Trying to make my program work with command line input, but spawning a new thread to handle the user input mixes things up. I'm sure this is very basic, but can't find a solution. Tried to fumble around a bit by passing System.in as method argument to the new thread and by copying stuff along with PipedStreams, but no success.. Dont know if the new Console class would be nice for this, but i'm using jdk1.4.2 where its not yet included.
Could any one give me some pointers how to do this proper?
Thanks
[537 byte] By [
Imiroa] at [2007-11-27 1:01:25]

# 1
Is the dummythread blocking on system.out or whats the problem?
Heres sample:
public class MultiThreadSystemOut
{
public static void start()
{
System.out.println("MultiThreadSystemOut.start");
new ExternalSystemOut().run();
new DummyThread().run();
System.out.println("MultiThreadSystemOut.start: end");
}
public static void main(String[] args)
{
MultiThreadSystemOut.start();
}
}
public class DummyThread implements Runnable
{
public void run()
{
long t1 = System.currentTimeMillis();
long t2 = t1 + (60 * 1000);
int counter = 0;
while(t2 - System.currentTimeMillis() > 0)
{
System.out.println("DummyThread.run: running happily for "+counter+" times.");
counter++;
try
{
System.out.println("DummyThread.run: waiting");
Thread.sleep(5000);
}
catch (InterruptedException e)
{
}
}
}
}
import java.io.IOException;
public class ExternalSystemOut implements Runnable
{
public void run()
{
try
{
System.out.println("ExternalSystemOut.run");
boolean run = true;
while (run)
{
if (System.in.available() > 0)
{
byte[] byteBuf = new byte[System.in.available()];
System.in.read(byteBuf);
String input = new String(byteBuf);
System.out.println("ExternalSystemOut.run: got some "+input);
if (input.indexOf("/q") > -1)
{
System.out.println("ExternalSystemOut.run: quitting");
run = false;
}
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Message was edited by: Imiro
Bummer, you should create Runnable like new Thread(runnable).start()... Topic closed.
Imiroa at 2007-7-11 23:36:18 >
