一分钟后立即停止线程 [英] Stop Thread right after one Minute

查看:236
本文介绍了一分钟后立即停止线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JButton来调用我的线程。但是我真正想要做的就是在一分钟后停止线程!
我的actionListener方法是:

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

t.start();
}

我的线程只运行一分钟,如下所示:

  public void run(){
int i; (!i = 0; i <= 100; i ++){

if(i == 100)
while(!Thread.currentThread()。isInterrupted()){
){
Thread.currentThread()。interrupt();

try {
Thread.currentThread()。sleep(600);
} catch(InterruptedException ex){
System.out.print(THREAD CLOSED);
return;
}

}
System.out.print(做BLA BLA);






$ b $问题:
我在一分钟后成功停止了线程,但是我无法做任何想要的事情。我只是想知道,我怎么才能达到这个目的,只需要一分钟就可以运行线程,而在线程内部,我想要做的事情!但是,如何?我错了这个方法吗?如果是,那么应该采取什么正确的做法?

解决方案

最简单的方法就是做一些像如下所示:

  public void run(){
long startTime = System.currentTimeMillis();
while(System.currentTimeMillis()< startTime + 60000){
//做一些有用的事情
}
}
pre>

做一些有用的事情应该是一个快速操作,并且您的线程总是会持续略长于1分钟(1分钟+做些有用的事情 )。

注意你原来的代码:从线程本身停止一个线程,不需要中断:你只需要从 run()方法。


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?

解决方案

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.

这篇关于一分钟后立即停止线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆