Sometimes in your Java application you need to run thread in background for your Timer application or any other application.. I’ve created simple application which starts thread in Background…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package com.crunchify.tutorials; /** * @author Crunchify.com * */ public class CrunchifyRunnableThread { public static void main(String[] args) { Runnable r = new Runnable() { public void run() { boolean flag = true; int i = 0; while(flag){ i++; System.out.println("Thread started... Counter ==> " + i); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } }; Thread t = new Thread(r); // Lets run Thread in background.. // Sometimes you need to run thread in background for your Timer application.. t.start(); // starts thread in background.. // t.run(); // is going to execute the code in the thread's run method on the current thread.. System.out.println("Main() Program Exited...\n"); } } |
Another must read:
Output of t.start():
1 2 3 4 5 6 7 |
Main() Program Exited... Thread started... Counter ==> 1 Thread started... Counter ==> 2 Thread started... Counter ==> 3 Thread started... Counter ==> 4 Thread started... Counter ==> 5 |
thread.run()
is going to execute the code in the thread’s run method on the current thread. You want thread.start()
to run thread in background.
Output of t.run():
1 2 3 4 5 |
Thread started... Counter ==> 1 Thread started... Counter ==> 2 Thread started... Counter ==> 3 Thread started... Counter ==> 4 Thread started... Counter ==> 5 |