java - 如何暂停/继续计划任务?
问题描述
我是 JAVA 新手,正在尝试学习一些并发概念。
我有一个简单的 GUI 类,它会弹出一个带有 1 个按钮的窗口,我想将其用于暂停/继续。
另外,我有一个扩展 TimerTask 的类,它如下所示并从 GUI 开始:
public class process extends TimerTask {
public void run() {
while(true) { /*some repetitive macro commands.. */ }
}
}
真正的问题是,如果已经暂停,如何暂停按钮的 onClick 任务并继续按钮的 onClick?
我已采取步骤使用布尔值来标记按钮,因为它会在每次单击时从暂停变为继续。
但是后来我不得不在while(button);
里面输入很多忙等待while()
......
你认为我可以Thread.sleep()
从任务线程之外进行类似或其他事情吗?
解决方案
旧答案
基本上,不支持 TimerTask 上的暂停和恢复,您只能取消,检查这里 也许您可能想阅读有关线程的信息,因为这是我所知道的具有中断和启动功能的替代方案,然后您可以跟踪你正在做的事情的进展,以恢复它停止的地方。
因此,我建议您通过此链接,因为您需要了解线程,而不仅仅是复制要使用的代码,那里有一个示例代码肯定也可以解决您的问题。
请注意,运行一个无休止的 while 循环基本上会导致您的程序没有响应,除非系统崩溃。在某一时刻,数据变得过载,程序就会溢出。这意味着它将失败。
.
新答案
因此,作为对新问题的回应,我能够运行一个很小的程序来演示如何在使用 SWING 时实现看起来像多线程的东西。
改写你的问题:你想运行一个无限期的任务,比如假设我们正在播放一首歌曲,然后点击一个按钮来暂停歌曲,再次点击应该继续歌曲吗?如果是这样,我认为下面的小程序可能对你有用。
public class Test{
static JLabel label;
static int i = 0;
static JButton action;
static boolean x = false; //setting our x to false initialy
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
label = new JLabel("0 Sec"); //initialized with a text
label.setBounds(130,200,100, 40);//x axis, y axis, width, height
action=new JButton("Play");//initialized with a text
action.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(action);//adding button in JFrame
f.add(label);
action.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
if(x){
x = false; //Update x here
action.setText("Play");
action.revalidate();
}else{
x = true; //Update x here also
action.setText("Pause");
action.revalidate();
if(x){ //Using x here to determind whether we should start our child thread or not.
(new Thread(new Child())).start();
}
}
}
});
f.setSize(500, 700);//500 width and 700 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
class Child implements Runnable{
@Override
public void run() {
while (x) {
//You can put your long task here.
i++;
label.setText(i+" Secs");
label.revalidate();
try {
sleep(1000); //Sleeping time for our baby thread ..lol
} catch (InterruptedException ex) {
Logger.getLogger("No Foo");
}
}
}
}
推荐阅读
- python - 更改一堆熊猫数据框的列顺序
- datatables - 按日期排序不适用于 Bootstrap 4 数据表
- c# - 如何将由 [ 和 ] 分隔的字符串转换为 C# 中的数组
- javascript - Playwright 无法评估返回的定义变量
- python - 如何从 MoviePy 中的视频中删除某些时间
- javascript - 两个圆之间的交点检测不起作用
- css - 如何在 Angular 材料中分离同一 html 中的组件?
- php - 通过终端更新作曲家时如何解决这个问题
- python-3.x - 为什么我不能使用 .bind 以与 tkinter 按钮列表中的命令标志相同的方式绑定函数
- kotlin - 如何更新变量以更改其值?(科特林)