ultithreading
M continue executing using notify() or notifyAll()
Java is a multi-threaded programming language which means we can develop multi 3)sleeping(Timed Waiting) − A runnable thread canenter the timed waiting
threaded program using Java. A multi-threaded program contains two or more parts state for a specified interval of time. A thread in this state transitions back to the
that can run concurrently and each part can handle a different task at the same time runnable state when that time interval expires or when the event it is waiting for
making optimal use of the available resources specially when your computer has occurs.
multiple CPUs. 5)Terminated (Dead) − A runnable thread enters theterminated state when
hread:- Thread is a single flow of control within a program. We can also say that
T it completes its task or otherwise terminates.
thread is a subprogram within a program. hread Priorities
T
Multi-threading enables you to write in a way where multiple activities can proceed Every Java thread has a priority that helps the operating system determine the
concurrently in the same program. order in which threads are scheduled.
Life Cycle of a Thread:- Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
A thread goes through various stages in its life cycle. For example, a thread is MAX_PRIORITY (a constant of 10). By default, every thread is given priority
born,started, runs, and then dies. The followingdiagram shows the complete life NORM_PRIORITY (a constant of 5).
cycle of athread. Thread.MIN_PRIORITY(), Thread.NORM_PRIORITY(),
Thread.MAX_PRIORITY(),
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 are very much platform
dependent.
Create a Thread by Implementing a Runnable InterfaceIf your
lass is intended to be executed as a thread then you can achieve this by
c
implementing a 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 a
Runnableinterface.Thismethodprovidesanentrypointforthethreadandyouwill
putyourcompletebusinesslogicinsidethismethod.Followingisasimplesyntaxof
the run() method −
public void run( )
Step 2:- As a second step, you will instantiate a Thread object using the following
constructor −
Following are the stages of the life cycle − Thread(Runnable threadObj, String threadName);
1)Newborn−Anewthreadbeginsitslifecycleinthenewstatewheniscreated Where, threadObj is an instance of a class that implements the Runnable interface
singnewkeyword.Itremainsinthisstateuntiltheprogramstartsthethread.It
u and threadName is the name given to the new thread.
is also referred to as a born thread. Step 3:- Once a Thread object is created, you can start it by calling start() method,
2)Runnable − After a newly born thread is started,the thread becomes runnable. which executes a call to run( ) method. Following is a simple syntax of start() method
A thread in this state is waiting for CPU timing. –
3)Running:-After runnable state when run() gets called,thread goes into void start();
running [Link] this satate thread is actually executing its task.
4)Blocked: −Thread goes into blocked state eitherof the following situation as Example
shown in above diagram ere is an example that creates a new thread and starts running it −
H
1)Either thread is suspended. Thread is again getsthe CPU timing by
calling resume(). class RunnableDemo implements Runnable {
2)waiting: Sometimes, a thread transitions to thewaiting state while the private Thread t;
thread waits for another thread to perform a task. A thread transitions back to private String threadName;
the runnable state only when another thread signals the waiting thread to
Thread: Thread
2
RunnableDemo( String name) { 2, 4
threadName = name; Thread: Thread-1, 3
[Link]("Creating " + threadName ); Thread: Thread-2, 3
} Thread: Thread-1, 2
Thread: Thread-2, 2
public void run() { Thread: Thread-1, 1
[Link]("Running " + threadName Thread: Thread-2, 1
); try { Thread Thread-1 exiting.
for(int i = 4; i > 0; i--) { Thread Thread-2 exiting.
[Link]("Thread: " + threadName + ", " + i); Create a Thread by Extending a Thread Class
// Let the thread sleep for a while. he second way to create a thread is to create a new class that extends Thread class
T
[Link](50); using the following two simple steps. This approach provides more flexibility in
} handling multiple threads created using available methods in Thread class. Step 1:-
}catch (InterruptedException e) { You will need to override run( ) method available in Thread class. This method
[Link]("Thread " + threadName + " interrupted."); provides an entry point for the thread and you will put your complete business logic
} inside this method. Following is a simple syntax of run() method − public void run( )
[Link]("Thread " + threadName + " exiting."); Step 2:- Once Thread object is created, you can start it by calling start() method,
} which executes a call to run( ) method. Following is a simple syntax of start()
method
public void start () { –
[Link]("Starting " + threadName ); oid start( );
v
if (t == null) { Example
t = new Thread (this, threadName); Here is the preceding program rewritten to extend the Thread −
[Link] (); class ThreadDemo extends Thread {
} } private Thread t;
} private String threadName;
public class TestThread { ThreadDemo( String name) {
public static void main(String args[]) { threadName = name;
RunnableDemo R1 = new RunnableDemo( "Thread-1"); [Link]("Creating " + threadName );
[Link](); }
RunnableDemo R2 = new RunnableDemo( "Thread-2"); public void run() {
[Link](); [Link]("Running " + threadName
} } ); try {
his will produce the following result −
T for(int i = 4; i > 0; i--) {
Output [Link]("Thread: " + threadName + ", " + i);
reating Thread-1
C // Let the thread sleep for a while.
Starting Thread-1 [Link](50);
Creating Thread-2 }
Starting Thread-2 }catch (InterruptedException e) {
Running Thread-1 [Link]("Thread " + threadName + " interrupted.");}
Thread: Thread-1, [Link]("Thread " + threadName + " exiting.");}
4 Running Thread
oid setPriority(int priority):-Sets the priority of this Thread object. The possible
v
public void start () { values are between 1 and 10.
[Link]("Starting " + threadName ); 5)public final void setDaemon(boolean on):-A parameterof true denotes
if (t == null) { this Thread as a daemon thread.
6)public final void join(long millisec):-The currentthread invokes this method
t = new Thread (this, threadName);
on a second thread, causing the current thread to block until the second thread
[Link] ();
terminates or the specified number of milliseconds passes.
} }
7)public void interrupt():-Interrupts this thread,causing it to continue execution if it
}
was blocked for any reason.
public class TestThread {
8)public final boolean isAlive():-Returns true ifthe thread is alive, which is
public static void main(String args[]) { any time after the thread has been started but before it runs to completion.
ThreadDemo T1 = new ThreadDemo( "Thread
1"); [Link](); he previous methods are invoked on a particular Thread object. The following
T
hreadDemo T2 = new ThreadDemo( "Thread-2");
T methods in the Thread class are static. Invoking one of the static methods
[Link]();
T performs the operation on the currently running thread.
} 1)public static void yield():- Causes the currentlyrunning thread to yield to any
} ther threads of the same priority that are waiting to be scheduled.2)public
o
This will produce the following result − static void sleep(long millisec):- Causes the currentlyrunning thread to block
Output for at least the specified number of milliseconds.
reating Thread-1
C 3)public static boolean holdsLock(Object x):- Returnstrue if the current
Starting Thread-1 thread holds the lock on the given Object.
Creating Thread-2 4)public static Thread currentThread():- Returnsa reference to the
Starting Thread-2 currently running thread, which is the thread that invokes this method.5)
Running Thread-1 public static void dumpStack():- Prints the stacktrace for the currently
Thread: Thread-1, running thread, which is useful when debugging a multithreaded application.
4 Running Thread
2 Thread: Thread Example
2, 4 he following ThreadClassDemo program demonstrates some of these methods
T
Thread: Thread-1, 3 of the Thread class. Consider a class DisplayMessage which implements
Thread: Thread-2, 3 Runnable −
Thread: Thread-1, 2 // Create a thread to implement Runnable
Thread: Thread-2, 2 public class DisplayMessage implements Runnable {
Thread: Thread-1, 1 private String message;
public DisplayMessage(String message) {
Thread: Thread-2, 1
[Link] = message;
Thread Thread-1 exiting.
}
Thread Thread-2 exiting.
public void run() {
Thread Methods
while(true) {
Following is the list of important methods available in the Thread class.
1)public void start():- Starts the thread in a separatepath of execution, then
[Link](message);
invokes the run() method on this Thread object. }
2)public void run():- If this Thread object was instantiatedusing a }
separate Runnable target, the run() method is invoked on that Runnable }
object. // Create a thread to extentd Thread
3)public final void setName(String name):-Changesthe name of the Thread public class GuessANumber extends Thread
object. There is also a getName() method for retrieving the name.4)public final {private int number;
public GuessANumber(int number) { [Link]("main() is
S
[Link] = number; ending...");
} }
public void run() { }
int counter = 0; This will produce the following result. You can try this example again and again
int guess = 0; and you will get a different result every time.
do { Output
guess = (int) ([Link]() * 100 + 1); Starting hello thread...
[Link]([Link]() + " guesses " + guess); Starting goodbye thread...
counter++; Hello
} while(guess != number); Hello
[Link]("** Correct!" + [Link]() + "in" + counter + "guesses.**"); Hello
} Hello
} Hello
Following is the main program, which makes use of the above-defined classes − Hello
public class ThreadClassDemo { Goodby
public static void main(String [] args) { e
Runnable hello = new DisplayMessage("Hello"); Goodby
Thread thread1 = new Thread(hello); e
[Link](true); Goodby
[Link]("hello");
e
[Link]("Starting hello thread..."); Goodby
[Link](); e
Goodby
unnable bye = new
R e
DisplayMessage("Goodbye"); Thread thread2 = ......
new Thread(bye);
[Link](Thread.MIN_PRIORITY); Inter-thread communication in Java
[Link](true); Inter-thread communication or Co-operation is all about allowing synchronized
[Link]("Starting goodbye thread..."); threads to communicate with each other.
[Link](); Cooperation (Inter-thread communication) is a mechanism in which a thread is
[Link]("Starting thread3..."); paused running in its critical section and another thread is allowed to enter (or
Thread thread3 = new lock) in the same critical section to be [Link] is implemented by following
GuessANumber(27); [Link](); methods of Object class:
try { wait() notify()
[Link](); notifyAll()
}catch(InterruptedException e) { 1)wait() method:- Causes current thread to releasethe lock and wait until either
[Link]("Thread interrupted."); another thread invokes the notify() method or the notifyAll() method for this object,
} or a specified amount of time has elapsed.
[Link]("Starting thread4..."); The current thread must own this object's monitor, so it must be called from the
Thread thread4 = new synchronized method only otherwise it will throw exception.
GuessANumber(75); public final void wait()throws InterruptedException waits until object is notified.
[Link](); public final void wait(long timeout)throws InterruptedException waits for the
specified amount of time. yThread t1=new MyThread();
M
2)notify() method- Wakes up a single thread thatis waiting on this object's MyThread t2=new MyThread();
monitor. If any threads are waiting on this object, one of them is chosen to be [Link]();
awakened. The choice is arbitrary and occurs at the discretion of the [Link]();
implementation. [Link]([Link]());
Syntax: [Link]([Link]());
public final void notify() }
3)notifyAll() method:- Wakes up all threads thatare waiting on this object's }
monitor. Syntax: Output :
public final void notifyAll()
r1
oining threads
J
true
Sometimes one thread needs to know when other thread is terminating. In
true
java, isAlive() and join() are two different methods that are used to check
r1
whether a thread has finished its execution or not.
r2
he isAlive() method returns true if the thread upon which it is called is still running
T
r2
otherwise it returns false.
Example of thread without join() method
final boolean isAlive()
But, join() method is used more commonly than isAlive(). This method waits until
ublic class MyThread extends Thread
p
the thread on which it is called terminates.
{
final void join() throws InterruptedException
public void run()
Using join() method, we tell our thread to wait until the specified thread completes
{
its execution. There are overloaded versions of join() method, which allows us to
specify time for which you want to wait for the specified thread to terminate. final [Link]("r1 ");
void join(long milliseconds) throws InterruptedException try {
As we have seen in the Introduction to MultiThreading, the main thread must [Link](500);
always be the last thread to finish its execution. Therefore, we can use Thread }
join() method to ensure that all the threads created by the program has been catch(InterruptedException ie){ }
terminated before the execution of the main thread. [Link]("r2 ");
}
Example of isAlive method public static void main(String[] args)
ublic class MyThread extends Thread
p {
{ MyThread t1=new MyThread();
public void run() MyThread t2=new MyThread();
{ [Link]();
[Link]("r1 "); [Link]();
try { }
[Link](500); }
} Output :
catch(InterruptedException ie) { } r1
[Link]("r2 "); r1
} r2
public static void main(String[] args) r2
{ In this above program two thread t1 and t2 are created. t1 starts first and after
rinting "r1" on console thread t1 goes to sleep for 500 ms. At the same time
p
1.Synchronized method.
Thread t2 will start its process and print "r1" on console and then go into sleep for
500 ms. Thread t1 will wake up from sleep and print "r2" on console similarly 2.Synchronizedblock.
thread t2 will wake up from sleep and print "r2" on console. So you will get output 3.static synchronization.
like r1 r1 r2 r2 Example of thread with join() method
2.Cooperation (Inter-thread communication in java)
public class MyThread extends Thread
{
Mutual Exclusive
public void run()
utual Exclusive helps keep threads from interfering with one another while sharing
M
{ data. This can be done by three ways in java:
[Link]("r1 ");
try { 1.by synchronized method
[Link](500);
2.by synchronized block
}catch(InterruptedException ie){ }
[Link]("r2 "); 3.by static synchronization
}
public static void main(String[] args) Concept of Lock in Java
{
ynchronization is built around an internal entity known as the lock or monitor.
S
MyThread t1=new MyThread(); Every object has an lock associated with it. By convention, a thread that needs
MyThread t2=new MyThread(); consistent access to an object's fields has to acquire the object's lock before
[Link](); accessing them, and then release the lock when it's done with them.
try{
[Link](); //Waiting for t1 to finish Java synchronized method
}catch(InterruptedException ie){}
If you declare any method as synchronized, it is known as synchronized method.
[Link]();
} } Synchronized method is used to lock an object for any shared resource.
Output :
r1 hen a thread invokes a synchronized method, it automatically acquires the lock for
W
r2 that object and releases it when the thread completes its task.
r1
r2 Synchronized Block in Java
In this above program join() method on thread t1 ensures that t1 finishes it process
ynchronized block can be used to perform synchronization on any specific
S
before thread t2 starts.
resource of the method.
Specifying time with join()
If in the above program, we specify time while using join() with t1, then t1 will uppose you have 50 lines of code in your method, but you want to synchronize
S
execute for that time, and then t2 will join it. only 5 lines, you can use synchronized block.
[Link](1500);
If you put all the codes of the method in the synchronized block, it will work same as
Doing so, initially t1 will execute for 1.5 seconds, after which t2 will join it. the synchronized method.
Thread synchronization:- * **Refer the example of thread synchronization shared on google
classroom.
here are two types of thread synchronization mutual exclusive and inter-thread
T
communication.
1.Mutual Exclusive