java 中如何使线程运行一定时间后停止

wylc123 1年前 ⋅ 322 阅读

主要此线程运行后可能1-2分钟无返回值,运行如果超过1分钟的,就要终止掉,线程只有自己关闭自己,而自己在运行,无法进行下一步代码的执行

/**
 * @author SongBin on 2018/11/16.
 */
import java.awt.event.*;
import javax.swing.Timer;
/*计时器*/
class Clock implements ActionListener{
    WorkThread wtd;
    Timer time;
    public Clock(WorkThread wtd){
        this.wtd=wtd;
        time=new Timer(10*60*1000,this);//每次间隔10分钟。
        time.setRepeats(false);
    }
    public void actionPerformed(ActionEvent e){
        time.stop();
    }
}
/*工作线程*/
class WorkThread extends Thread{
    Clock temp;
    int i=0;
    public WorkThread(){
        temp=new Clock(this);
    }
    public void run(){
        temp.time.start();
        while(1==1){
            /*工作空间*/
            System.out.print(i+" ");
            i++;
            /*工作空间*/
            if(!temp.time.isRunning()){
                System.out.println("End");
                return;//杀线程,停止线程运行
            }
        }
    }
}
public class Main
{
    public static void main(String[] args) {
        WorkThread wtd =new WorkThread();
        wtd.start();
    }
}
更多内容请访问:IT源点

相关文章推荐

全部评论: 0

    我有话说: