java线程中断代码_需要一个基于Java的可中断定时器线程

这看起来是一个更优雅的解决方案,特别是考虑到我以前没有使用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;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值