Java creates a background thread that does something periodically

Is it possible to create a separate background thread that will separately do some things? I tried the following program, but it does not work as I expect.

public class Test { private static class UpdaterThread extends Thread { private final int TIMEOUT = 3000; public void run() { while (true) { try { Thread.sleep(TIMEOUT); System.out.println("3 seconds passed"); } catch (InterruptedException ex) { } } } } /** * @param args * the command line arguments */ public static void main(String[] args) { try { Thread u = new UpdaterThread(); u.start(); while (true) { System.out.println("--"); } } catch (Exception ex) { ex.printStackTrace(); } } } 

I expected that every 3 seconds "3 seconds have passed" will be printed in the stream of several lines "-". In fact, “3 seconds have passed” is never printed. What for? And how can I create a background thread that will do something regardless of the main thread?

+7
source share
5 answers

Use java.util.TimerTask and java.util.Timer :

 Timer t = new Timer(); t.scheduleAtFixedRate( new TimerTask() { public void run() { System.out.println("3 seconds passed"); } }, 0, // run first occurrence immediately 3000); // run every three seconds 
+13
source

He prints "It's been 3 seconds." Remove System.out.println("--") and you will see them more easily; -)

Now you can also use ScheduledExecutorService and use Runnable instead of Thread :

 public class Test { private static class Updater implements Runnable { @Override public void run() { System.out.println("3 seconds passed"); } } public static void main(String[] args) throws InterruptedException { Runnable r = new Updater(); ScheduledExecutorService service = Executors.newScheduledThreadPool(1); service.scheduleAtFixedRate(r, 0, 3, TimeUnit.SECONDS); Thread.sleep(10000); service.shutdown(); } } 
+6
source

You can use the above approach to run stuff periodically, although TimerTask might be simpler.

As for your output, I suspect that your main thread does not allow UpdaterThread to run because it is in a very narrow loop. Please note that this will depend on the available CPU / cores, etc.

Are you considering sleeping in your main thread or using Thread.yield () ? Please note the reservations on this related page:

When to use yield ()?

I would say almost never. Its behavior is not standard and, as a rule, the best ways to perform the tasks that you perform may need to be performed with yield (): if you try to use only parts of the processor, you can do this by estimating how much the processor used the thread in the last piece of processing, then they sleep for some time to compensate: see the sleep () method;

Also pay attention to this interesting article on handling thread interrupts.

+3
source

I would recommend using a ScheduledExecutorService . To run UpdaterThread() every 3 seconds, you can do the following:

 ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.scheduleAtFixedRate(new UpdaterThread(), 0, 3000, TimeUnit.MILLISECONDS); 

You can read more here: Java Tutorials - Artist Interfaces .

+1
source

There are many answers, but no one says why his example did not work. System.out is the output stream, so after you start writing to this stream, JAVA blocks it, and all other threads will wait until the lock is applied to the stream. After the thread is unlocked, another thread will be able to work with this thread.

To make your example work, you must add Thread.sleep to the while in the main thread.

+1
source

All Articles