Re: Help in Threading when program waits for an input
Mithil wrote:
I am using the following line to get input from the user in the
command prompt.
BufferedReader dis = new BufferedReader(new
InputStreamReader(System.in));
The program does nothing until the user enter a value into it, is it
possible to use threads and do more work while waiting for the input.
If so how can I do it any code examples would be great :)
Threading is difficult.
For this example, assuming you just want to read lines of input and poll
for results:
final BlockingQueue<String> input =
new java.util.concurrent.ArrayBlockingQueue<String>(10);
Thread thread = new Thread(new Runnable() {
public void run() {
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in)
);
for (;;) {
String line = in.readLine();
if (line == null) {
break;
}
put(line);
}
} catch (java.io.IOException exc) {
// Oops... (perhaps should quit)
throw new Error(exc);
} finally {
put(null);
}
}
private void put(String line) {
for (;;) {
try {
input.put(line);
return;
} catch (java.lang.InterruptedException exc) {
// Ignore - we should keep going.
// IO may throw, however.
}
}
}
});
thread.setDaemon(true);
thread.setPriority(6);
thread.start();
outerLp: for (;;) {
while (!input.isEmpty()) {
String line = input.remove();
if (line == null) {
// End of input.
break outerLp; // say
}
... do stuff with line ...
}
... do a little stuff while waiting ...
}
(Disclaimer: Not tested or even compiled.)
Tom hawtin