Threads: Life Cycle of A Thread
Threads: Life Cycle of A Thread
Thread Priorities:
Every Java thread has a priority that helps the operating system determine the order
in which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1)
and MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be
allocated processor time before lower-priority threads. However, thread priorities
cannot guarantee the order in which threads execute and very much platform
dependent.
Create Thread by Implementing Runnable Interface:
If your class is intended to be executed as a thread then you can achieve this by
implementing Runnable interface. You will need to follow three basic steps:
Step 1:
As a first step you need to implement a run() method provided by Runnable
interface. This method provides entry point for the thread and you will put you
complete business logic inside this method. Following is simple syntax of run()
method:
public void run( )
Step 2:
At second step you will instantiate a Thread object using the following
constructor:
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface
and threadName is the name given to the new thread.
Step 3
Once Thread object is created, you can start it by calling start( ) method, which
executes a call to run( ) method. Following is simple syntax of start() method:
void start( );
Example:
Here is an example that creates a new thread and starts it running:
classRunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo( String name){
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(inti = 4; i> 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start ()
{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
}
}
Create Thread by Extending Thread Class:
The second way to create a thread is to create a new class that extends Thread
class using the following two simple steps. This approach provides more flexibility
in handling multiple threads created using available methods in Thread class.
Step 1
You will need to override run( ) method available in Thread class. This method
provides entry point for the thread and you will put you complete business logic
inside this method. Following is simple syntax of run() method:
public void run( )
Step 2
Once Thread object is created, you can start it by calling start( ) method,
which executes a call to run( ) method. Following is simple syntax of
start() method:
void start( );
Example:
Here is the preceding program rewritten to extend Thread:
classThreadDemo extends Thread {
private Thread t;
private String threadName;
ThreadDemo( String name){
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(inti = 4; i> 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start ()
{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
ThreadDemo T1 = new ThreadDemo( "Thread-1");
T1.start();
ThreadDemo T2 = new ThreadDemo( "Thread-2");
T2.start();
}
}
Thread Methods:
Following is the list of important methods available in the Thread class.
Methods with Description
public void start()
1 Starts the thread in a separate path of execution, then invokes the run() method on
this Thread object.
public void run()
2 If this Thread object was instantiated using a separate Runnable target, the run()
method is invoked on that Runnable object.
public final void setName(String name)
3 Changes the name of the Thread object. There is also a getName() method for
retrieving the name.
public final void setPriority(int priority)
4
Sets the priority of this Thread object. The possible values are between 1 and 10.
public final void setDaemon(boolean on)
5
A parameter of true denotes this Thread as a daemon thread.
public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current
6
thread to block until the second thread terminates or the specified number of
milliseconds passes.
public void interrupt()
7 Interrupts this thread, causing it to continue execution if it was blocked for any
reason.
public final booleanisAlive()
8 Returns true if the thread is alive, which is any time after the thread has been
started but before it runs to completion.
The previous methods are invoked on a particular Thread object. The following
methods in the Thread class are static. Invoking one of the static methods performs
the operation on the currently running thread.
Methods with Description
public static void yield()
1 Causes the currently running thread to yield to any other threads of the same
priority that are waiting to be scheduled.
public static void sleep(long millisec)
2 Causes the currently running thread to block for at least the specified number of
milliseconds.
public static booleanholdsLock(Object x)
3
Returns true if the current thread holds the lock on the given Object.
public static Thread currentThread()
4 Returns a reference to the currently running thread, which is the thread that
invokes this method.
public static void dumpStack()
5 Prints the stack trace for the currently running thread, which is useful when
debugging a multithreaded application.
Example:
The following ThreadClassDemo program demonstrates some of these methods of
the Thread class. Consider a class DisplayMessage which implements Runnable:
// File Name : DisplayMessage.java
// Create a thread to implement Runnable
publicclassDisplayMessageimplementsRunnable
{
privateString message;
publicDisplayMessage(String message)
{
this.message= message;
}
publicvoid run()
{
while(true)
{
System.out.println(message);
}
}
}
Following is another class which extends Thread class:
// File Name : GuessANumber.java
// Create a thread to extentd Thread
publicclassGuessANumberextendsThread
{
privateint number;
publicGuessANumber(int number)
{
this.number= number;
}
publicvoid run()
{
int counter =0;
int guess =0;
do
{
guess=(int)(Math.random()*100+1);
System.out.println(this.getName()
+" guesses "+ guess);
counter++;
}while(guess != number);
System.out.println("** Correct! "+this.getName()
+" in "+ counter +" guesses.**");
}
}
Following is the main program which makes use of above defined classes:
// File Name : ThreadClassDemo.java
publicclassThreadClassDemo
{
publicstaticvoid main(String[]args)
{
Runnable hello =newDisplayMessage("Hello");
Thread thread1 =newThread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.start();
Runnable bye =newDisplayMessage("Goodbye");
Thread thread2 =newThread(bye);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setDaemon(true);
System.out.println("Starting goodbye thread...");
thread2.start();
System.out.println("Starting thread3...");
Thread thread3 =newGuessANumber(27);
thread3.start();
try
{
thread3.join();
}catch(InterruptedException e)
{
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 =newGuessANumber(75);
thread4.start();
System.out.println("main() is ending...");
}
}
Synchronization in Java:
Synchronization in java is the capability of control the access of multiple threads to
any shared resource.
Java Synchronization is better option where we want to allow only one thread to
access the shared resource.
Uses of Synchronization:
The synchronization is mainly used to
To prevent thread interference.
To prevent consistency problem.
Types of Synchronization
There are two types of synchronization
Process Synchronization
Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
Mutual Exclusive
Synchronized method.
Synchronized block.
static synchronization.
Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while
sharing data. This can be done by three ways in java:
by synchronized method
by synchronized block
by static synchronization
wait()
notify()
notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a specified
amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.
Method Description
public final void wait()throws InterruptedException waits until object is notified.
public final void wait(long timeout)throws waits for the specified amount
InterruptedException of time.
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are
waiting on this object, one of them is chosen to be awakened. The choice is
arbitrary and occurs at the discretion of the implementation. Syntax:
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
Why wait(), notify() and notifyAll() methods are defined in Object class not
Thread class?
Let's see the important differences between wait and sleep methods.
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
is the method of Object class is the method of Thread class
is the non-static method is the static method
is the non-static method is the static method
should be notified by notify() or after the specified amount of time, sleep
notifyAll() methods is completed.