How do you re-call Thread in Java?

I want the thread to run in the background every 500 milliseconds. To do this, I expanded Thread, implemented ActionListener, and placed the class that I extended to Timer. The timer calls run () every 500 milliseconds. However, my entire Swing GUI freezes when this thread downloads material from the Internet. I want it to run in the background without freezing the GUI while it waits for I / O to complete. I am also a bootloader to complete the download before we wait 500 milliseconds.

gogogo () is called to initialize the entire process:

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();
}
}
+3
source share
5 answers

, loop Thread.sleep(500L) . , , , 500 . , .

+8

java ScheduledExecutorService. .

java:

, Swing, , GUI, Swing , , , GUI, . , ,

+1

, (doStuff), , . , , .

, TimerTask

public class Downloader extends TimerTask {
    public void run() {
        doStuff();
    }
}

... elsewhere ...

Timer myTimer = new Timer();

public void gogogo() {
    myTimer.scheduleAtFixedRate(new Downloader(), 0, 500);
}

, 500 , ​​500 . , myTimer.cancel(), .

+1
source

You need to start a thread for every timer action. Calling the run run () method does not start the thread.

public void actionPerformed(ActionEvent e) 
{
        //run();
Downloader t = new Downloader();
t.start();

}

It might be better to use an anonymous class for actionlistener. Sorry my java syntax, but I have not tested it ...

  new Timer(500, 
      new ActionListener(){
            public void actionPerformed(ActionEvent e) 
            {
               //run();
               Downloader t = new Downloader();
               t.start();

            }
          }).start();

Or without a timer ...

public static void gogogo()
{
        t= new Downloader();
        t.start();

}

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

        Thread.sleep(500);
    }
}
0
source

Hmm, most likely all you have to do is reduce the priority of the stream, so it does not feed on all of your resources.

-1
source

Source: https://habr.com/ru/post/1704799/


All Articles