首页 > 解决方案 > 如何暂停/继续计划任务?

问题描述

我是 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()从任务线程之外进行类似或其他事情吗?

标签: java

解决方案


旧答案

基本上,不支持 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");
                }
            } 
        }
    }

推荐阅读