Create Thread using Anonymous inner class

As briefed, a Thread is light weight process.

Below is an example, on how to create and start Thread, using Anonymous inner class.

Create Anonymous inner class, which extends from java.lang.Thread and override public void run() method.

public class ThreadAnonymousInnerClass {
	public static void main(String args[])
	{
		Thread t1=new Thread(){
		public void run(){
		for(int i=0;i<=10;i++){
		try{
		System.out.println("Thread t1: "+i);
		Thread.sleep(100);  //100 milliseconds
		}catch(InterruptedException e){
		System.out.println("Exception:"+e.getMessage());
		}
		}
		}
		};

		t1.start();

		for(int i=0;i<=10;i++){
		try{
		System.out.println("Main Thread: "+i);
		Thread.sleep(100);  //100 milliseconds
		}catch(InterruptedException e){
		System.out.println("Exception:"+e.getMessage());
		}
		}
	}
}

Create Anonymous class by implementing Runnable interface

How to create Thread, using anonymous class for Runnable. In below example, we are creating object of an anonymous class which implements Runnable interface.

public class ThreadAnonymousRunnable {
	public static void main(String args[])
	{
		new Thread( new Runnable() {
		    public void run() {

              for(int i=0;i<10;i++)
    	      {
    		System.out.println("child_thread: "+i);
    		try
    		{
    			Thread.sleep(100);
    		}catch(InterruptedException ie){
    			System.out.println(ie.getMessage());
    		}
    	     }
		    }
		}).start();

		for(int i=0;i<10;i++)
    	        {
    		System.out.println("main_thread: "+i);
    		try
    		{
    			Thread.sleep(100);
    		}catch(InterruptedException ie){
    			System.out.println(ie.getMessage());
    		}
    	        }
	}
}

Further reducing size of code

public class ThreadAnonymousRunnable {

	private static void thread_body(String thread_name)
	{
		for(int i=0;i<10;i++)
    	{
    		System.out.println(thread_name+": "+i);
    		try
    		{
    			Thread.sleep(100);
    		}catch(InterruptedException ie){
    			System.out.println(ie.getMessage());
    		}
    	}
	}

	public static void main(String args[])
	{
		new Thread( new Runnable() {
		    public void run() {

		    	thread_body("child_thread");
		    }
		}).start();

		thread_body("main_thread");
	}
}

You may also like to read:
purpose of synchronized keyword
how to use synchronized with a class
how to use synchronized with a method
what are concurrent collections

Leave a Reply