我已经在一个单独的类中用java实现了一个向下计数器,它有一个以秒为单位的开始时间开始向下计数到零但是当它达到零时我需要它在其他文件中制作一些线程来停止它们的工作我怎么能这样做?
这是我的柜台代码:
public class Stopwatch {
static int interval;
static Timer timer;
public void start(int time) {
Scanner sc = new Scanner(System.in);
int delay = 1000;
int period = 1000;
timer = new Timer();
interval =time;
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
// System.out.println(setInterval());
setInterval();
}
}, delay, period);
}
public int time() {
return interval;
}
private static final int setInterval() {
if (interval == 1)
timer.cancel();
return --interval;
}
}
提前感谢。
答案 0 :(得分:1)
根据其他线程正在做什么,我建议中断或设置一个布尔值(并在另一个线程中检查)。如果可以随时停止执行其他线程,则使用中断,但是如果在某个时间点之后无法停止执行,只需在输入该代码之前设置/检查布尔值。
在秒表类中添加一个布尔值:
private static boolean continue = true;
创建一个检查布尔值的方法:
public static boolean shouldContinue() {
return this.continue;
}
修改你的setInterval()
以更改布尔值:
private static final int setInterval() {
if (interval == 1)
continue = false;
return --interval;
}
在其他课程的某处添加支票:
if (!(Stopwatch.shouldContinue())) {
return;
}
或
if (Stopwatch.shouldContinue()) {
//do work here
}
由于听起来我的评论有所帮助,我想我会把它变成一个答案,所以我们可以从未答复的清单中删除它。