这看起来是一个更优雅的解决方案,特别是考虑到我以前没有使用scheduledExecutorService。但我仍然在努力把所有的碎片拼凑在一起!我不确定Worker是否以及何时调用它的45秒倒计时?另外,我的目的是让这样一个工作人员在遇到一行stdout时重新开始倒计时,基本上将倒计时重置为一个新的45秒窗口。这有助于澄清。
当我将scheduleExecutorService合并到我的解决方案中时,这里是我使用线程复制它的整个示例代码。让我知道你能不能早点拿到。我可以在我遇到的每一个新的stdout上调用一个线程,但是在声明的时间窗口没有中断的情况下,我不能优雅地处理这个情况:(希望代码中的注释足够详细,以传达我的意图,否则请告诉我,我可以澄清:
import java.io.BufferedReader;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.channels.Channels;
public class InterruptInput {
static BufferedReader in = new BufferedReader(
new InputStreamReader(
Channels.newInputStream(
(new FileInputStream(FileDescriptor.in)).getChannel())));
boolean TimeUp = false;
public static void main(String args[]) {
try {
System.out.println("Enter lines of input (user ctrl+Z Enter to terminate):");
System.out.println("(Input thread will be interrupted in 10 sec.)");
// interrupt input in 10 sec
String line = in.readLine();
while ((line.compareTo("") != 0)) {
System.out.println("Read line:'"+line+"'");
TimeOut ti = new TimeOut();
Thread t = new Thread(ti);
t.start();
if((line = in.readLine()) != null) {
t.interrupt();
}
}
System.out.println("outside the while loop");
} catch (Exception ex) {
System.out.println(ex.toString()); // printStackTrace();
}
}
public static class TimeOut extends Thread {
int sleepTime = 10000;
private volatile Thread threadToInterrupt;
public TimeOut() {
// interrupt thread that creates this TimeOut.
threadToInterrupt = Thread.currentThread();
setDaemon(true);
}
public void run() {
System.out.println("starting a new run of the sleep thread!!");
try {
sleep(10000); // wait 10 sec
} catch(InterruptedException ex) {/*ignore*/
System.out.println("TimeOut thread interrupted!!");
//I need to exit here if possible w.out executing
//everything after the catch block
}
//only intend to come here when the 10sec wait passes
//without interruption. Not sure if its plausible
System.out.println("went through TimeOut without interruption");
//TimeUp = true;
}
}
}