问题
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?
回答1:
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.
回答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.
来源:https://stackoverflow.com/questions/16455765/stop-thread-right-after-one-minute