Thread - 1
Thread - 1
LIFECYCLE OF A THREAD: -
During the lifetine ofa thread, there are many states it can ente,.7 ny include:
I. Newlorn state
2. Runnable statc
3. Runing state
1. Blocking state
5. Dead state
Athread is always in one of these five states, It can move from s n8 sute to another
Via a varicty of waysas showm in th¹ folpwgfigre on the next page:
New Thread Newborn
Start stop
Active
Thrcad Runaing Runnable stop
yicld
Dead
suspcndod
sleep resume ThrKIlcikadd
wait notify Stop
Idle Thread
(Not Runnable) Blocked
yield
resume(O
after t
notify
Running Runnable
Relinguishlng control using wait (Q method Wait ng
Blocking State:
Athread is said to be
blocked when it is prevented from entering into th
state and subsequently the running
sleeping, or waiting in order to satisfystate. This happens when the thread is
"not runnable" but nTt dead there fully certain requirements. Ablocked thread is
qualified to run again.
Dead State:
Every thread has a life
executing its run() method. It iscycle. A running thread ends its
a natural dead, life when it has co
imessage to it at any state thus causing a However, we can kill it by sendine
it is born, or while it is premature
running, or even when it is in death to it. A thread can be killed
"not runnable"(blocked) conditin
Java's mul:ithreading systern is built upon
companion interfac:, Runnable. Thread the Thread class, its
directBy refer to the ethereal (n. encapsulates a thread of methods,
through its proxy, the tlread instanceheavenly) state of a running thread, cxecution.
we should
We
deal,
will either extend Tt reai or that produced it. To create a
new thread our p
To start the executionimpletnent the Runnable
interface.
object. The code that executesofina athread, we should call the start() nnethod for the
declared like: publ; void run). Threads new thread is always a
other than the main method called run(). s
start in the run() thod for the
are unable to call nun object that represents the thrcad.thread
But
in a program i
method to start a here is a proble
object representing the thread and that thread, we should call the siart( ) method f
to stop the
exeçution o' athread that causes the run()
is running, we method to bc called. When we
Thrcad object. This is tecause, the should call the stop( ) methoda
and new threads
thread can o1ly created and are always run and managcd by
run() method ourselves. it bewould started by the operating system. If
operating s;
we were t0
thread as the program that calls it.simply operate like any other method, running in the s
are calling a native code When we call the start() method for a
from which the rum) method method that causes the operating thread objcuk
for the system to initiate another t
thread by calling the start() method. thread object executes. Hence we should sarti
Whenever we calla
supply an appropriate exceptionthread method that is likely to throw an
one of the following forms: handler to catch it. The çommon catchexception, we f"
statement ntay
catch( IllegalThrcadState Exception c)
java. lang,. Object
t--java.lang.Thro wable
to-java.lang.Exception
t--java.lang.RuntimeException
t--java.lang.l egalArgumentException
to-java.lang.llegalThreadStateException
Thrown to indicate that a thread is not in an
operation. appropriate state for the requested
catch( ThrcadDeath c)
java.lang. Object
to-java.lang. Throwable
t--java.lang.Error
+-java.lang. ThreadDeath
public class ThreadDeath extends Error
An instance of ThreadDeath is thrown in the victim thread when the stop metlhod with
zero arguments in class Thread is called,
An application should catch instances of this class only if it must clean up after being
terminated asynchronously. If ThreadDeath is caught by a method, it is inportant that it be
rethrown so that the thread actualy dies.
catch(Intcrruptedxccption c)
java. lang.Object
to-java. lang.Throw able
When a Java program starts up, one thread begins running imnediately. This
Is usually called the nuinihread ofour program. This thread is important in two ways, one -
t acts as the parent for other child threads and two - in most of the cases, it is the last thread
which ends up after performing various shutdown actions. It is created automatically when
the program starts exccution and can be controlled through a Thread
must obtain areference to the thread in which it is called using the follc
stalic Thread current Thread() cwiobjngeck,tmetTohod:
PROGRAM 1
* Demo Program: Controlling the main thread
class MainThread
for(int i=5;>0;i-)
{
System.out.printin("t"+i);
/*suspend a thrcad for a period of time
*Syntax: statie void sleep(long milliseconds, in,
throws InterruptedException nanoseconds)
*nanoseconds paramneter is meant for the environ1me1nt that allows i
Thread.sleep(1000);
/^sleep) method may throw an exception of
thread wanted to interrupt this sleeping thread.following type if some other
catch(InterruptedException e)
System.out.printin("Main thrcad interrupted"):
* OUTPUT:
Current thread before renaming: Thrcad[main,5,main]
Current thread after renaming: My Thread
4
2
1
Thread t;
NewThread()
llcreate a new second thread
/* passing this as the first argument indicates that we want the new thread to call the
run() method on this object */
t=new Thread(this, "Domo Thread");
System.out.printin(" Childthread: "+t);
l/start the thread
L.start();
public void run()
try
for(int i=5;0;i-)
System.o.printtn("tChild i= "+i);
Thread.slep(500);
catch(Inter uptedException e)
System.out.println(" Child thread interrupted");
class ThreadDriver
for(int i-5;0;i-)
Systen.out.printin(" Main i"4i);
Thrrad.l2ep(1000);
catch(lnterruptedException e)
System.o it.print1n(" Main thread interrupted");
NewThread()
l/createa new second thread
super("DomoThread");
System.out.println(" Child thread: "+this);
I/start the thread
start);
try
{
for(int i-5;j>0;i--)
System.out.println("tChildi= "+):
Thread.sleep(500);
catch(InterruptedException e)
Systeim.0ut.pritln(" hild thrend nterrupt."
System.ou.pritln(" Existing from child thread");
class ThreadDriverl
try
for(int i=s;i>0;i--)
System.out.printIn(""+name+"; "+i):
L.sleep(1000):
catch(lnterruptedF'xception c)
Systerm.out.println(name+" interrupted");
System.out.printn(" Existing from thread "+name):
class ThreadDriver2
try
/0UTPUT:
New Thread: Thread[First,5,main
New Thread: Thread[Second,5,main]
New Thread: ThreadfThird,5,main)
First: 5
Third: 5
Second: 5
i"irst: 4
hird: 4
Second: 4
First: 3
Third: 3
Second: 3
First: 2
Third: 2
Second: 2
First: 1
Third: 1
Second: 1
Existing from thre:ul First
Existing from thrcad Third
Existing from thread Second
Existing from nair: thread */
PROGRAM S
/" use
threadt11ethods
* This prograrn must belike yiBa(),
çompiled stop(), etc.,
*/
using th¹following
command line ar:zument
CAjprglthread>javay.d ThreadDriverfava
Cjprg\ThreadDri
Note: lthread>'avvacer3,ThrjavaeadDrusesiyoreD3.java a
Note: Recompile with overrides
-deprécation for déprecatedAPI.
details.
CAjprglthread> javacf4 ThreadDriver3,java
class Aextends Thread
public void r1n()
for(int i-1;jei;it+)
if(i==)
yicld();
System.out.println("t Thread A::i= "+);
System.out.printIn(" Exit from thread A");
class B cxtcnds
Thrcad
public void run()
for(int j-10;j<-50jt=\)
System.out.println("\t Thrcad B::j= "i):
if js= 30)
Støp);
System:out-printa(" Exit from thread B"):
Stop ()3
class ThreadDriver3
Yielding a thrcad
When a thread hus nothing to do, it 'can call the yield() metho.I of its Thrcad og
This method tells the scheduler to run a differenn thread. The value of c:iling :icld()
largely on whether the scheduling mechanisn1 for the platform on which the progam is
running is preemptive ornonpreemptive.
By choosing a maximum length of timc a thrcad can continuously run, a premptive
scheduling mechanism guarantees that no single thread uses more than its fair share of the
processor. If a thread runs for that amount of time without yielding control to another thrcad.
the scheduler preempts the thread and causes it to stop running so that another thread can
run.
A nonpreemptive scheduling mechanism cannot preempt threads. A nonpreemptive
scheduler relies on the individual threads to yield control of the processor frequently, so that
it can provide reasonable performance. A thread explicitly yields control by calling the
Thread object's yield() method. More often, however, a thrcad implicitly yiclds contrul whcn
it is forced to wait for something to happen elsewhere.
Calling a Thread object's yield() method during a lengthy computation can be quite
valuable on a platform that uses a nonpreemptive scheduling mechanism, 1s it allows other
threads to run. Otherwise, the lengthy computation can prevent other threads from running.
On aplatform that uses a preemptive scheduling mechanism, calling yield( ) does not usually
make any noticeable difference in the responsiveness of threads.
Regardless of the scheduling algorithm that is being used, youshoud not naike any
assumptions about when a thread willbe scheduled to run again after it has caled yield(). If
you want to prevent a thread from being scheduled to run until a specified anount of tinme has
elapsed, youshould call the sleep() method of the Thread object. The sleep) method takes
an argument that specifies a minimun number of miliseconds that must elapse before the
thread can be scheduled to run again.
String name;
Thread t;
NewThread(String n)
name-n;
tnew Thread(this,ame);
System.out.prirntin(" New thread: "+n);
t.start();
public void run()
try
class ThreadDriver5
class ThreadDriveró
{
public static void main(String[] args)
{
Thread.currentThread).setPriority(Thread.MAX_ PRIORITY);
clicker hi-new clicker(Thread.NORM_ PRIORITY+2);
clicker lo=new clicker(Thread. NORM PRIORITY-2);
hi.start();
lo.start();
try
Thread.sleep(10000);
catch(InterruptedException e)
{
System.out.println(" 1.Main thread interrupted");
hi.stop);
lo.stop():
try
hi.t.join();
lo.tjoin);
catch(]InterruptedBxception e)
System.out.printin(" 2. Main thread interruped");
OUTPUT:
C:jprglthread>java Thread Driveró
Low-priority thread: 74080696
High-priority thread: 1294026743
C:jprglthread>java ThreadDriverQ
Low-priority thread: 78366351
High-priority thread: 1284370770
C:\jprglthread>java ThreadDriveró
Low-priority thread: 77497285
High-priority thread 12.32576928
SYNCHRONIZATION:
When two or i.cre threads need access to a shared
resource they
ensure that the resource will be used by only one thread at time. The pr nced some var
achieved is called synchronization. Alike other languages, Java pro Tcess es
by which thi
level support for it. unique, languag
Key to synchronization is the concept of the monitor (also
A.R. Hoare first defined this age-old mechanism. We can val1ed a semaplhore).
box that can hold only one thread. Once a thread enters a think of a monitor as a very sm
until that thread exits the monitor. In this way, a monitor all ot er thrcads Ust wa
monitor can be u ed protect a sh:rel ass
from being manipulated by more than one thread at a time.
A monitor is an object that is used as a mutually
thread can own a monitor at a given time. When a threadexclusie
le or mutex. Only on
acqui s I,:ck it is saicd to hau
entered the monitor. All other threads attempting to enter tie bc
suspended until the first thread exits the monitor. These other th ads irecedsaidnonitor will &
to b: waity
for the monitor.
There exists two mechanisms of synchronization and both ol tl em
synchronized. Any time that we have a method, or a group of method thatusemanipulaies
the kcvwor
th
internal state of an object in a multithreaded situation, we should use sy
to guard the state from race condition, 1chronized evwon
PROGRAMI
Program obiective: The next program docs not use
the first one, Callme, has a single method named
synchronizution. Jhere are threv classes
parameter called msg. This method tries lo print thecalI(). The call() mcthod takes a S/ring
msg string insde dsquare brackets.
After call() prints the opening bracket and the msg
pauses he current thread for one second. string, it calls Threadsleep(1000), which
The
reference to an instance of the callme class and a constrctor to next class, Caller, takes a
respectively. The constructor also creates a new String, which are stored in target and msg,
thrcad tht will cal! this objet's runl )
method The thread is started
immedlately,
method on the target Instance of Callme, The run( ) method of Caller calls
starts by creating a passing in the msg string, Finally the the call( )
Synch class
unique message string.single Instance of Callme, and three instances oj
The same instance of Callme is passed toeaclh Caller, cach with a
Caller.
I/This program is not
synchronized
class Callme
Thread.sleep(1000);
catch(InterruptedException e)
System.out.printin(" Iterrupted from call( )");
System.out,printin(" ]");
/* OUTPUT:
CAjprglthread>jav[.
[Jayanta
Synch
[Bishnu Ser ]
[
*/