Thread Creation

Creating a Thread:

In the most general sense, we create a thread by instantiating an object of type Thread. Java identifies two ways in which this can be accomplished:

  1. We can implement the Runnable interface
  2. We can extend the Thread class, itself.
Implementing Runnable:

The easiest way to create a thread is to create a class that implements the Runnable interface. To implement Runnable, a class need only implement a single method called run( ).

public void run( )

Inside run( ) method, we will define the code that constitutes the new thread. The run( ) can call other methods, use other classes and declare variables, just like the main thread.

The only difference is that run( ) establishes the entry point for another, concurrent thread of execution within our program. This thread will end when run( ) returns.

After we create a class that implements Runnable, we will instantiate an object of type Thread from within that class using one of the following constructors:

Thread(Runnable threadObj)
Thread(Runnable threadObj, String threadName)

Here threadObj is the object whose run method is called and thread Name is the new threads name. After the new thread is created, it will not start running until we call start( )method.

The start( ) method puts the thread in the ready queue (runnable state). Whenever the thread gets scheduled its execution will start from the run( ) method.

Example
		class A implements Runnable
		{
		public void run()
		{
		for(int i=1;i<=5;i++)	
		{
		System.out.println(“Child Thread:” + i);
		}
		System.out.println(“Exiting child thread”);
		}
		}
		class RunnableTest
		{
		public static void main(String args[])
		{
		A a1=new A();
		Thread t1 = new Thread(a1,”Demo Thread”);
		t1.start();
		System.out.println(“Main thread exiting”);
		}
		}
	
Output

Main thread exiting

Child Thread:1

Child Thread:2

Child Thread:3

Child Thread:4

Child Thread:5

Exiting child thread

Example 2
		class A implements Runnable
		{
		Thread t;
		A()
		{
		t= new Thread(this, “Demo Thread”);
		System.out.println(“Child thread: “+ t);
		t.start();
		}
		public void run()
		{
		for (int i=1; i<=5; i++)
		{
		System.out.println(“Child Thread: ”+ i );
		try
		{
		Thread.sleep(500);
		}
		catch (InterruptedException e)
		{
		System.out.println(e);
		}
		}
		System.out.println (“Exiting Child thread”);
		}
		}
		class RunnableTest2
		{
		public static void main (String args[] )
		{
		A a1=new A();
		for (int i=1; i<=5; i++)
		{
		System.out.println (“Main Thread:”+ i);
		try
		{
		Thread.sleep (1000);
		}
		catch(InterruptedException e)
		{
		System.out.println(“main thread interrupted”);
		}
		}
		System.out.println(“End of Main thread”);
		}
		}
	
Output:

Child thread: Thread[Demo Thread,5,main]

Main Thread:1

Child Thread: 1

Child Thread: 2

Main Thread:2

Child Thread: 3

Child Thread: 4

Main Thread:3

Child Thread: 5

Exiting Child thread

Main Thread:4

Main Thread:5

End of Main thread

Extending Thread class:

The second way to create a thread is to create a new class that extends Thread, and create an instance of that class. The extending class must override the run() method, which is the new thread's entry point. It must also call start() to be the execution of the new thread.

Example
		class A extends Thread
		 {
		 A( )
		 {
		 super (“Test Thread”);
		System.out.println (“Child thread:” + this);
		start();
		}
		public void run ()
		 {
		for (int i=1; i<=5; i++)
		{
		System.out.println(“Child Thread:”+i);
		try
		{
		sleep(500);
		}
		catch(InterruptedException e)
		{
		System.out.println(“Child thread interrupted”);
		}
		}
		System.out.println (“Exiting Child thread”);
		}
		}
		class ThreadTest
		{
		public static void main(String args[])
		{
		new A();
		for (int i=1; i<=5; i++)
		{
		System.out.println(“Main Thread: “+i);
		try
		{
		Thread.sleep(1000);
		}
		catch(InterruptedException e)
		{
		System.out.println(“Main thread interrupted”);
		}
		}
		System.out.println (“Main thread exiting”);
		}
		}
	
Output:

Child thread:Thread[Testing Thread,5,main]

Main Thread: 1

Child Thread:1

Child Thread:2

Main Thread: 2

Child Thread:3

Child Thread:4

Main Thread: 3

Child Thread:5

Exiting Child thread

Main Thread: 4

Main Thread: 5

Main thread exiting

Note:-

If Thread is not assigned any name, it will be something like: Thread-1, Thread-2, Thread-3 etc.

Choosing an Approach:

The thread class defines several methods that can be overridden by a derived class. Out of these methods, the only one that must be overridden is run(). That is, of course the same method required when we implement the Runnable interface.

Many Java programmers feel that classes should be extended only when they are enhanced or modified in somehow. So, if we will not be overriding any of Thread’s other methods, it is probably best to implement Runnable interface.

Creating Multiple Threads:
		class A implements Runnable
		{
		String name;
		Thread t;
		A(String threadName)
		{
		name=threadName;
		t=new Thread(this, name);
		System.out.println(“Child thread:”+t);
		t.start();
		}
		public void run()
		{
		for(int i=1;i<=5;i++)
		{
		System.out.println(t.getName()+ “:” + i);
		try
		{
		Thread.sleep(1000);
		}
		catch(InterruptedException e)
		{
		System.out.println(e);
		}
		}
		System.out.println(name+ “Exiting”);
		}
		}
		class MultiThreadTest
		{
		public static void main(String args[] )
		{
		A a1=new A(“One”);
		A a2=new A(“Two”);
		A a3=new A(“Three”);
		try
		{
		Thread.sleep(10000);
		}
		catch(InterruptedException e)
		{
		System.out.println(“main thread interrupted”);
		}
		System.out.println (“Main thread exiting”);
		}
		}
	
Output:

Child thread:Thread[One,5,main]

Child thread:Thread[Two,5,main]

Child thread:Thread[Three,5,main]

One:1

Two:1

Three:1

One:2

Two:2

Three:2

One:3

Two:3

Three:3

One:4

Two:4

Three:4

One:5

Two:5

Two:5

Three:5

OneExiting

TwoExiting

ThreeExiting

Main thread exiting

Imposing some Ordering by using isAlive() and join() Methods:

Often we will want the main thread to finish last. One way to achieve this is to call sleep( ) within main. This is rather crude (rough) way. Two ways exist to determine whether a thread has finished. First, we can call isAlive() on the thread. This method is defined by Thread, and its general form is:

final boolean isAlive( )

The isAlive() method returns true if the thread upon which it is called is still running. It returns false otherwise. While isAlive( ) is occasionally useful, the method that we will more commonly use to wait for a thread to finish is called join( ), shown here:

final void join( ) throws InterruptedException

This method waits until the thread on which it is called terminates. Additional forms of join( ) allow us to specify a maximum amount of time to wait for the specified thread to terminate.

The following example makes uses join( ) to ensure that the main thread is the last to stop. It also demonstrates the isAlive( ) method.

Example
		class A implements Runnable
		{
		String name;
		Thread t;
		A(String threadName)
		{
		name=threadName;
		t=new Thread(this,name);
		System.out.println(“Child thread:”+t);
		t.start();
		}
		public void run()
		{
		for(int i=1;i<=5;i++)
		{
		System.out.println(name + “:”+ i );
		try
		{
		Thread.sleep(1000);
		}
		catch(InterruptedException e)
		{
		System.out.println(e);
		}
		}
		System.out.println(name + “Exiting”);
		}
		}
		class DemoJoin
		{
		public static void main(String args[] )
		{
		A ob1=new A(“One”);
		A ob2=new A(“Two”);
		A ob3=new A(“Three”);
		System.out.println(“Thread One is alive?:”+ob1.t.isAlive());
		System.out.println(“Thread Two is alive?:”+ob2.t.isAlive());
		System.out.println(“Thread Three is alive?:”+ob3.t.isAlive());
		try
		{
		ob3.t.join();
		ob2.t.join();
		ob1.t.join();
		}
		catch(InterruptedException e)
		{
		System.out.println(“main thread interrupted”);
		}
		System.out.println(“Thread One is alive?:”+ ob1.t.isAlive());
		System.out.println(“Thread Two is alive?:”+ob2.t.isAlive());
		System.out.println(“Thread Three is alive?:”+ob3.t.isAlive());
		System.out.println (“Main thread exiting”);
		}
		}
	
Output:

Child thread:Thread[One,5,main]

Child thread:Thread[Two,5,main]

Child thread:Thread[Three,5,main]

Thread One is alive?:true

Thread Two is alive?:true

Thread Three is alive?:true

One:1

Two:1

Three:1

One:2

Two:2

Three:2

One:3

Two:3

Three:3

One:4

Two:4

Three:4

One:5

Two:5

Three:5

OneExiting

TwoExiting

ThreeExiting

Thread One is alive?:false

Thread Two is alive?:false

Thread Three is alive?:false

Main thread exiting

Copyright 1999- Ducat Creative, All rights reserved.