Creating and Starting Threads

In Java, there are two ways to create a thread

-------Implements the Runnable.jave interface.

-------Instantiating a subclass that inherits Thread.java

Using Runnable Interface(just need know the concept )

public interface Runnable() {

public void run();

}

There is only one method defined in Runnable interface; run(). Any class implements this interface have to provide its own version of implementation of run() method.

/*create thread from Runnable imterface*/

class Worker2 implements Runnable

{

public void run() {

System.out.println("I Am a Worker Thread ");

}

}

public class Second

{

public static void main(String args[]) {

Runnable runner = new Worker2();

Thread thrd = new Thread(runner);

thrd.start();

System.out.println("I Am The Main Thread");

}

}

/*create thread from Thread class*/

class Worker1 extends Thread

{

public void run() {

System.out.println("I Am a Worker Thread");

}

}

public class First

{

public static void main(String args[]) {

Worker1 runner = new Worker1();

runner.start();

System.out.println("I Am The Main Thread");

}

}

Creating a Thread

Instantiating a subclass of thread.java

/*AThread class implements a thread that */

/*sleeps and outputs a computation */

class AThread extends Thread {

static int Range = 10000;

int input;

public AThread( int y ) { input = y; }

public void compute() {

int howLong = (int)(Math.random() * Range);

try {

sleep( howLong );

} catch (InterruptedException e) { };

System.out.println("input = " + input + " squared = " + input*input);

}

public void run() { compute(); }// required by Java

}

Now consider a program, th1.java, that spawns a thread. The main thread (most likely) terminates before the spawned thread does.

class th1 {

public static void main(String[] args) {

AThread t = new AThread(7); // create thread

t.start(); // start thread (at t.run())

System.out.println("Main Done");

// main exits here; t continues

}

}

Output:

Main Done

input = 7 squared = 49

Note that the main thread (the thread that is given to main()) terminates before thread t.

Multiple Threads

Now consider a program that spawns multiple threads (th2.java). It's not much different than the previous:

/* th2 shows how to create three threads, a, b, and c. */

class th2 {

public static void main(String[] args) {

// Step 1: create threads

AThread a = new AThread(1);

AThread b = new AThread(2);

AThread c = new AThread(3);

// Step 2: start all threads

a.start();

b.start();

c.start();

// Step 3: main thread exits here, presumably before

// a, b, or c are finished

System.out.println("Main done");

}

}

Output:

Main done

input = 2 squared = 4

input = 3 squared = 9

input = 1 squared = 1

Note: that the order in which threads start may not be the order in which they complete. (The reason is that each thread is alive for a different length of time). Run th2 several times to see this.

Joining a Thread

Now suppose that threads a, b, c must be executed in this

order. The Thread class provides a x.join() method, where x is a thread. x.join() will cause the calling thread to wait until thread x is terminated.

/* th3 shows how to run three threads, a, b, and c/

/* sequentially. Program illustrates the join() method*/

class th3 {

public static void main(String[] args)

throws InterruptedException {

// Step 1: create threads

AThread a = new AThread(1);

AThread b = new AThread(2);

AThread c = new AThread(3);

// Step 2: start first thread, wait, start second, wait...

a.start();

a.join();

b.start();

b.join();

c.start();

c.join();

// Step 3: main thread exits here

System.out.println("Main Done");

}

}

Output:

input = 1 squared = 1

input = 2 squared = 4

input = 3 squared = 9

Main Done

Suspending & Resuming a Thread

/* th4 creates three threads: a, b, and c. b and c*/

/* suspend themselves immediately, a runs to completion */

/* and resumes b; b runs to completion and so on*/

class MoreThread extends AThread {

MoreThread cont;

Boolean pause;

public MoreThread(int x, MoreThread y, boolean z)

{ super(x); cont = y; pause = z; } //constructor

public void run() {

if (pause) suspend();

compute();

if (cont != null)

cont.resume();}}

class th4 {

public static void main(String[] args)

throws InterruptedException {

MoreThread c = new MoreThread(3,null, true);

MoreThread b = new MoreThread(2,c, true);

MoreThread a = new MoreThread(1,b, false);

// start threads in opposite order

c.start(); b.start(); a.start();

System.out.println("Main Done");}}

Note: the order in which threads are created and started is important. Thread creation order is last-to-finish-is-created-first. Same for starting.

Output:

Main Done

input = 1 squared = 1

input = 2 squared = 4

input = 3 squared = 9

Stopping a Thread

A thread can die for two reasons:

1.Its stop() method is called.

2.End of scope of run() methods is reached(There is

no more code for thread to execute).

class DThread extends Thread {

DThread(String name){

super(name);} //constructor

public void run() {

try{

System.out.println(getName() + " is active.");

sleep(500);

} catch(ThreadDeath Death){

System.out.println("Uhhh " + getName() + " is being killed or something.(Thread Death caught)");

throw(Death);

} catch(InterruptedException e){}

}

}

class DeathDemo {

public static void main(String args[]) {

// Create some DThread objects

DThread Beavis, Butthead;

//Initialize the objects

Beavis = new DThread("Beavis");

Butthead = new DThread("Butthead");

// Start the objects

Beavis.start();

Butthead.start();

try{

// Main thread sleep for a little

Thread.sleep(500);

} catch(InterruptedException e){}

// Kill Beavis thread

Beavis.stop();

// Kill Butthead thread

Butthead.stop();

}}

output:

Beavis is active.

Butthead is active.

Uhhh Beavis is being killed or something.(Thread Death caught)

Uhhh Butthead is being killed or something.(Thread Death caught)

Note:other features/operations on threads used in above example

Thread(String s):constructor that allows threads to be given name s

getName():returns name of thread

Priorities of Threads

Java assigns priorities to threads for thread scheduling. Top priority is 10, lowest priority is 1.Normal priority is 5. Program th6.java prints these numbers.

/* th6 queries the priority values of threads. */

class th6 {

public static void main(String[] args) {

AThread t = new AThread(7); // create thread

t.start(); // start thread (at t.run())

System.out.println("t's priority "+t.getPriority());

System.out.println(Thread.MIN_PRIORITY);

System.out.println(Thread.NORM_PRIORITY);

System.out.println(Thread.MAX_PRIORITY);

System.out.println("Main Done"); // main exists

}

}

Output:

t's priority 5

1

5

10

Main Done

input = 7 squared = 49

Note: setPriority(int i) - sets the thread's priority to i

Other Features of Threads

There are other features/operations on threads that are "interesting". Among them are:

currentThread()----returns reference to currently executing thread object

isAlive() -----tests if thread is alive

join(long m) -----waits for at most m milliseconds for thread to die

yield()-----causes currently executing thread object to temporarily pause and allow other threads to execute

interrupt( ) -----wakes up a waiting or sleeping thread (with an InterruptedException) or sets an "interrupted" flag on a non- sleeping thread.

interrupted( ) ----- a thread can test its own "interrupted" flag

isInterrupted( ) ----- a thread can test the "interrupted" flag of another thread.