threads
New Thread with Runnable
With this example we are going to demonstrate how to create a Thread with a Runnable. We have created a Thread with a Runnable as described below:
- We have created
ThreadWithRunnableExample
that implements Runnable and overrides itsrun()
API method. In this method the Runnable’s thread sleeps using sleep(long millis) API method of Thread. - We create a new Thread with this runnable, and all its
start()
method so that its execution begins.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; public class ThreadWithRunnableExample implements Runnable { public static void main(String[] args) { Thread t = new Thread(new ThreadWithRunnableExample(), "Child Thread"); t.start(); for (int i = 0; i < 2; i++) { System.out.println("Main thread : " + i); try { Thread.sleep(100); } catch (InterruptedException ie) { System.out.println("Main thread interrupted! " + ie); } } System.out.println("Main thread finished!"); } @Override public void run() { for (int i = 0; i < 2; i++) { System.out.println("Child Thread : " + i); try { Thread.sleep(100); } catch (InterruptedException ie) { System.out.println("Child thread interrupted! " + ie); } } System.out.println("Child thread finished!"); } }
Output:
Main thread : 0
Child Thread : 0
Main thread : 1
Child Thread : 1
Main thread finished!
Child thread finished!
This was an example of how to create a Thread with a Runnable in Java.