View RSS Feed

My Java Tips

Creating a Thread (extending Java Thread Class)

Rate this Entry
by , 11-13-2011 at 10:41 AM (3777 Views)
There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. An instance of the subclass can then be allocated and started. The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started.


In case, where the class extends a Tread class, it must override run() method of the Thread class. The program may override the other methods also. Following listing shows these steps clearly.

Java Code:
class MyThread extends Thread {
MyThread ( )     {
…………..
…………..
}         

public void run ( ) //must override     {
………….
………….
}    

 ………..
} 

public class Example1 {
public static void main()     {
MyThread t = new MyThread ();
………….
t.start () ;
………….
}
}
Below is the list of the important Thread class constructors.

Thread()
Allocates a new Thread object.

Thread(Runnable target)
Allocates a new Thread object.

Thread(Runnable target, String name)
Allocates a new Thread object.

Thread(String name)
Allocates a new Thread object.

Thread(ThreadGroup group, Runnable target)
Allocates a new Thread object.

Thread(ThreadGroup group, Runnable target, String name)
Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group.

Thread(ThreadGroup group, String name)
Allocates a new Thread object.

Below is the list of important methods of the Thread class.

static int activeCount()
Returns the number of active threads in the current thread's thread group.

void checkAccess()
Determines if the currently running thread has permission to modify this thread.

static Thread currentThread()
Returns a reference to the currently executing thread object.

static int enumerate(Thread[] tarray)
Copies into the specified array every active thread in the current thread's thread group and its subgroups.

long getId()
Returns the identifier of this Thread.

String getName()
Returns this thread's name.

int getPriority()
Returns this thread's priority.

Thread.State getState()
Returns the state of this thread.

ThreadGroup getThreadGroup()
Returns the thread group to which this thread belongs.

static boolean holdsLock(Object obj)
Returns true if and only if the current thread holds the monitor lock on the specified object.

void interrupt()
Interrupts this thread.

static boolean interrupted()
Tests whether the current thread has been interrupted.

boolean isAlive()
Tests if this thread is alive.

boolean isDaemon()
Tests if this thread is a daemon thread.

boolean isInterrupted()
Tests whether this thread has been interrupted.

void join()
Waits for this thread to die.

void join(long millis)
Waits at most millis milliseconds for this thread to die.

void join(long millis, int nanos)
Waits at most millis milliseconds plus nanos nanoseconds for this thread to die.

void run()
If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.

void setContextClassLoader(ClassLoader cl)
Sets the context ClassLoader for this Thread.

void setDaemon(boolean on)
Marks this thread as either a daemon thread or a user thread.

void setName(String name)
Changes the name of this thread to be equal to the argument name.

void setPriority(int newPriority)
Changes the priority of this thread.

static void sleep(long millis)
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.

static void sleep(long millis, int nanos)
Causes the currently executing thread to sleep (cease execution) for the specified number of milliseconds plus the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers.

void start()
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

Let us now write a program that creates a thread that prints a string n number of times. This program creates the thread by extending thread class:

Java Code:
class MyThread {
	public static void main(String args[]) {
		MyThread t = new MyThread("Java", 50);
		t.start();
	}
}

class MyThread extends Thread {
	private String str;

	private int num;

	MyThread(String s, int n) {
		str = new String(s);
		num = n;
	}

	public void run() {
		for (int i = 1; i <= num; i++)
			System.out.print(str + " ");
	}
}
Program in above listing creates a class called MyThread which is a subclass of Thread class. The run method of this class prints a string n number of times. The main class PrintString1 creates an object (thread) of MyThread class and uses the start ( ) method to run the thread that print the string “Java” 50 number of times.

Output:


Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java
Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java
Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java

Please note that a better way to create a thread in Java is to implement Runnable interface.

Submit "Creating a Thread (extending Java Thread Class)" to Facebook Submit "Creating a Thread (extending Java Thread Class)" to Digg Submit "Creating a Thread (extending Java Thread Class)" to del.icio.us Submit "Creating a Thread (extending Java Thread Class)" to StumbleUpon Submit "Creating a Thread (extending Java Thread Class)" to Google

Comments