This is a code modification from the Java Concurrency Tutorial
package threads;
public class SimpleThreads {
static void threadMessage(String msg) {
String threadName = Thread.currentThread().getName();
System.out.format("%s: %s%n", threadName,msg);
}
private static class MessageLoop implements Runnable{
@Override
public void run() {
String[] importantInfo= {"apple","bat","chlorine","dog","egg","fog","gun"};
try {
for(int i=0;i<importantInfo.length;i++) {
Thread.sleep(4000);
threadMessage(importantInfo[i]);
}
}catch(InterruptedException ie) {
threadMessage("i wasn't done");
}
}
}
public static void main(String[] args) throws InterruptedException{
long patience = 100;
if(args.length > 0)
try {
patience = Long.parseLong(args[0]) * 1000;
}catch(NumberFormatException nfe) {
System.err.println("argument must be a integer");
System.exit(1);
}
threadMessage("starting message loop thread");
long startTime = System.currentTimeMillis();
Thread t = new Thread(new MessageLoop());
t.start();
threadMessage("waiting for messageloop thread to finish");
while(t.isAlive()) {
threadMessage("still waiting...");
if(((System.currentTimeMillis() - startTime) > patience) && t.isAlive()) {
threadMessage("tired of waiting");
t.interrupt();
}
}
threadMessage("finally");
}
}
and this is the conclusion
main: starting message loop thread
main: waiting for messageloop thread to finish
main: still waiting...
main: still waiting...
...(repeats about 100 times)
main: still waiting...
main: still waiting...
main: still waiting...
main: still waiting...
main: tired of waiting
main: still waiting...
main: tired of waiting
main: still waiting...
main: tired of waiting
main: still waiting...
main: tired of waiting
main: still waiting...
main: tired of waiting
Thread-0: i wasn't done
main: finally
I expected that after the first (and presumably only) main: tired of waitingI will see Thread-0: i wasn't done, but main: tired of waitingwill appear 5 times - why is this?
source
share