3

I'm new to JAVA and trying to learn some concurrency concepts.
I have a simple GUI class that pops-up a window with 1 button which I want to use for pause/continue.
Also, I have a class that extends TimerTask, it looks like below and start with the GUI:

public class process extends TimerTask {
  public void run() { 
     while(true) { /*some repetitive macro commands.. */ }
  }
} 

Real question is, how can I pause the task onClick of the button and also continue onClick of the button if already paused?

I have taken a step to use a boolean to flag the button as it changes from pause to continue on each click.

But then I had to type a lot of while(button); for busy waiting inside the while()...
Do you think I can make like Thread.sleep() or something but from outside the task thread?

Wale
  • 1,644
  • 15
  • 31

1 Answers1

1

OLD ANSWER

Basically, there is no support for pause and resume on TimerTask, you can only cancel, check here perhaps you might want to read about threading as that's the alternative I know of that has an interrupt and start features and then you can keep track of the progress of what you're doing to resume where it stopped.

So, I will suggest you go through this link, because you need to understand threading not just copy a code to use, there is a sample code there that will definitely solve your problem also.

Note that running an endless while loop will basically cause your program not to respond, unless the system crashes. At a certain point, the data becomes an overload and the program will overflow. This means it will fail.

.

NEW ANSWER

So, response to the new question, I was able to run a tiny little program to demonstrate how you can achieve something that looks like multithreading when working with SWING.

To rephrase your question: You want to run an indefinite task like let say we're playing a song, and then onclick of a button to pause the song, on click again should continue the song?, if so, I think below tiny program might work for you.

    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");
                }
            } 
        }
    }
Wale
  • 1,644
  • 15
  • 31
  • hi that was really interesting thanks. can you explain about the note, why my program will crash and how to prevent maybe? i just want some macro commands to be executed in a loop forr few hours until i want it to stop. – junior_developer181 Nov 25 '19 at 14:36
  • @Tezro are you using SWING for the GUI? – Wale Nov 26 '19 at 14:27
  • yea, im using intellij and swing for the gui. – junior_developer181 Nov 26 '19 at 16:51
  • I will recommend you go through https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html Swing itself is single threaded and that might be a blocker. Meanwhile, I will update the answer above. – Wale Nov 26 '19 at 19:15
  • @Tezro I will modify your question above to suite the main topic. – Wale Nov 26 '19 at 20:18
  • While the idea of a child thread makes sense, you can't update the UI in a thread other than the GUI thread. At least you can't update it the way you are doing. See https://stackoverflow.com/questions/7229284/refreshing-gui-by-another-thread-in-java-swing – AndyMan Nov 26 '19 at 21:05
  • @AndyMan I have same feeling also, I should not be able to update the UI thread but If you pay attention to label.revalidate(); it find a way to lock on the UI thread and update it. Run the code to confirm this. – Wale Nov 26 '19 at 21:56
  • @AndyMan we might also look at it this way: since JLabel is basically using the UI thread, and the static instance of it is what we're referencing, I want to believe it has connection to the UI thread one way or the other that I don't know for now regardless of where it's been called from. if you check revalidate() method, it speaks more about the way it gains the UI thread and update it's component accordingly. – Wale Nov 26 '19 at 22:10
  • So how do I make the "assumed thread" (that runs the song, right?) actually pause when x==false? is it happens automatically? (i guess not..) – junior_developer181 Nov 26 '19 at 23:56
  • @Tezro run the code and you will get what you need, assumed thread is just me playing around, I have updated the post. – Wale Nov 27 '19 at 00:05