你如何反复调用Java中的线程?

Pen*_*ant 3 java multithreading

我想要一个线程每500毫秒在后台执行一次.为此,我扩展了一个Thread,实现了ActionListener并将我扩展的类放入Timer中.Timer每500毫秒调用run().但是,当这个线程从Internet下载东西时,我的整个Swing GUI都会冻结.我希望它在后台运行,而不会在等待IO完成时冻结GUI.在我们等待500毫秒之前,我也是下载器完成下载.

调用gogogo()来初始化整个过程:

public final class Downloader extends Thread implements ActionListener
{
public static void gogogo()
{
    t= new Downloader();
    new Timer(500, (ActionListener) t).start();

}

public void run() 
{
    doStuff(); //the code that i want repeatedly called
}

public void actionPerformed(ActionEvent e) 
{
    run();
}
}
Run Code Online (Sandbox Code Playgroud)

Wil*_*ler 8

只需启动一次线程,使其循环,并执行Thread.sleep(500L)每次迭代.每隔500毫秒启动一个全新的线程可能更有意义.如果可以避免,就没有理由承担相关费用.