0

I got an answer from my last question. But now I am unable to use and stop the Thread just after one minute after doing my things. I actually want to close/stop the thread after one minute after doing my things. So, I'm badly confused: how can I do this using:

public class Frame2 extends javax.swing.JFrame implements Runnable{
    public Frame2() {
        initComponents();
    }

    public void run(){
        long startTime = System.currentTimeMillis();
        while (( System.currentTimeMillis() - startTime ) < 1000) {        
            System.out.print("DOING MY THINGS");
        }
    }
}

The problem is that it is not working at all and when I close the frame containing this Thread the line of code

    System.out.print("DOING MY THINGS");

works in an infinite loop.

Thanks in advance.

Community
  • 1
  • 1
Tech Nerd
  • 822
  • 1
  • 13
  • 39

1 Answers1

3

when I close the frame containing this Thread

Frame does not contain threads. Frame can have a reference to it. But the thread itself will run until it's execution is complete (run method ends) and not a second less.

You can not just "stop" the Thread. It must always complete it's execution (again, run method to end).

The code you wrote should be working pretty well and stop writing stuff in 60 seconds. If you want it to terminate on you closing the frame, you should add some variable to check against and write true to it when you want the thread to terminate.

Example:

private volatile boolean terminated = false;

public void run(){
  long startTime = System.currentTimeMillis();
  while (!terminated && System.currentTimeMillis() < startTime + 60000) {
    System.out.print("DOING MY THINGS");
    // here I want to do my things done in just one minute
    // and after that I want to stop the thread at will!
  }
}

public void stop() {
  terminated = true;
}
Boann
  • 48,794
  • 16
  • 117
  • 146
bezmax
  • 25,562
  • 10
  • 53
  • 84
  • actually the system.out command is not working when I start the thread and when I just click the JFrame close button the Thread stops itself executing the system.out.print command in an infinite loop – Tech Nerd May 09 '13 at 07:21
  • Then we need to see more of your code, the error is somewhere else. The thread looks pretty ok by itself. – bezmax May 09 '13 at 07:22