1

I have a JButton to invoke my thread. But what I actually want to do is to stop the thread just after the one minute! My actionListener Method is:

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    new Frame2().setVisible(true);
    Thread t=new Thread(new Frame2());

    t.start();
    }    

My thread to run for only one minute is as follow:

    public void run(){
    int i;
    while(!Thread.currentThread().isInterrupted()){
        for(i=0;i<=100;i++){

            if(i==100){
            Thread.currentThread().interrupt();
             }
        try {
            Thread.currentThread().sleep(600);
        } catch (InterruptedException ex) {
            System.out.print("THREAD CLOSED");
           return;
        }

    }
        System.out.print("DOING THINGS BLA BLA");
    }

}    

The Problem: I have stopped the thread after one minute successfully, but I was not able to do anything desired in it. I just want to know that how can I achieve this in order to run the thread for only one minute and inside the thread I want to do my things! But how? Am I wrong with this approach? If, yes then what should be the right approach?

Tech Nerd
  • 822
  • 1
  • 13
  • 39

2 Answers2

4

The simplest way to do what you want is to have something like the following:

public void run() {
    long startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() < startTime + 60000) {
        // do something useful
    }
}

"do something useful" should be a fast operation, and your thread will always last slightly longer than 1 minute (1 minute + the time of "do something useful").

Note about your original code: to stop a thread from the thread itself, no need for an interrupt: you just need to return from the run() method.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • I am using this logic but how to get out of this while loop after the required time? – Tech Nerd May 09 '13 at 06:57
  • The wile loop stops after the reguire time, because System.currentTimeMillis() returns the current time each time the loop condition is evaluated. – JB Nizet May 09 '13 at 08:44
  • How do I ensure that i exit out of while loop if my task is short enough and is completed before the wait time. E.g. If "// do something useful" completes in 10 seconds, I don't want to keep running it inside the while loop - 1 minute is just maximum timeout that I want, not the "mandatory"/minimum - do I just introduce a Boolean flag to keep the status of task use "break" or is there a better way? – Tintin Oct 03 '17 at 23:08
2

To be sure that your thread will work 1 minute you need to create separate thread for that.

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
   new Frame2().setVisible(true);
   final Thread t=new Thread(new Frame2());

   t.start();
   new Thread(new Runnable() {
     @Override
     public void run() {
       TimeUnit.SECONDS.sleep(1);
       t.interrupt();
     }
   }).start();
 }   

Now regardles of what your "t" thread is doing, it will be killed after 1 minute.

Grzegorz Gajos
  • 2,253
  • 19
  • 26
  • If it work I will be So much thankful to you please wait for my mark! – Tech Nerd May 09 '13 at 06:51
  • Yes, you're right, "t" thread should check for `if (Thread.interrupted())` and then for example throw `InterruptedException` to stop execution. This is I believe most recommended option. In theory you could use deprecated `Thread.stop()` but is deprecated and you shouldn't :). – Grzegorz Gajos May 10 '13 at 07:14