0% found this document useful (0 votes)
6 views

Thread - 1

Uploaded by

PRODYOT SINHA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Thread - 1

Uploaded by

PRODYOT SINHA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

THREADING

A multitlreaded program contains two or more partsthat canrún concurrerntly. Each


art of suclh a program iscalled a thread and cach thread defines a separate path of execution.
Thus. multit1reading is a specialization form of multitasking.
There are tvo distinct types of multitasking: process-based and tread-based. A
orcesx is a program that is executing. Thus, process-based multitasking is the feature that
llows your computer to run two or more programs concurrently. For e> ample, process based
multitasking enables us to run MS-word for editing a word docut« nt i. the sarme. time
unnig media player to listen some sweet music. In processed based inulti:asking a program
s the smallest unit of code that can be dispatched by a scheduler. (A Trocess migrates
Detween the various scheduling queues throughout its lifetime. The cperat ing system `must
sclect, for scheduling purposes, processes from these queues in sole fashion. The
appropriate scheduler carries out the selection process).
On the other hand in thread-based multitasking system, the thred is the smallest unit
of dispatch able code. That is, a single program can perform twc or more tasks
Simutaneously. For instance, a user can simultaneously type in characters and run the spell"
checker within the same process.
A thread, sometimes called a lighiweight process (LWP), is a tasic unit of CPU
uilization; it comprises a thread ID, a program counter, a register set. and a stack. It shares
with other threads belonging to the same process4its code section, iata scction, and othcr
operating system resources, such as open files afd signals. A traditional (or heavweigh)
process has a single thread of coatrol, If the process has multiple threacs of control. it can do
more than one task at a time. Hence a multitasking thread requires fevwer overheads than
multitasking processes.

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

State transition diagram ofathread


Newborn State:
When we create a thread object, the
The thread is not yet thread is born and is said, to be
scheduled running. At this state, we can do
for in
things with it: only one newborf nol
ofthe
Schedule it for running using start() method.
Kill it by using stop()
If scheduled, it moves to the Runnable state. If
stage, an exception will be thrown. we attempt to use any other method a

start Newborn stop


Runnable D:ad
State
state

Scheduling anewborn thread


Runnable State:
The runnable state means that the
execution and i.e. for the availability of the thread is ready for execution and is
processor, That is, the thread has joinedwaiting
of threads that are waiting for the qw
execution. Java
determines how that thread should be treated with assigns each thread a priority (an
used to decide when to switch from one respect to the others. A threadintege.
priot
Switch. The rule that determine when a running thread to the nexs. This is called co:
A thread can context switch takes place are simple:
A
voluntarily give up control.
in case ofhigher-priggity
thread
can preempt a thread.
ir them inthreads"whitequal priority, some OS' 1ike
round-robin (US tourmament in whichWin-98 allocate time-slice automaiot
fasbjon. On some other OS, threads of equal priority cach competitor plays every
must
thrcad with cqual priority. 1lowever, if we want a thrcad to voluntarily yield cotro t
give up cCntrolto another u
of equal priority before its turn comes, we can do so by using the yicld( ) nethod.

yield

Running Thrcad O-O


Relinguish control using yield() method
Running State:
Running means that the processor, has given its time to the thread for its execution.
The thread runs until it relinquish (v. to give sth, up) control on its own or it is preempted (v. .
to prevent sth. happening by taking action to stop it) by a higher priority thread. Arunning.
thread may relinquish its control in one of the following situation.
1. It bas been suspended using.suspend( ) method. Asuspended thread can be revived
by using the resume( ) method. This approach is useful when we want to suspend a
thread for some time due to certain reason, but do not want to kill it.
suspend( )

resume(O

Running Runnable Suspended,


Relinguishing control using suspend) method
2. It has been made to sleep. We can put a thread to sleep for a specified tine period
using the method slcep( time )where time is in milliseconds. This is that the thread is
out of queuc during this period. The thrcad re-enters the runnable state as soon as this
time period is elapsed.
slcep( t )

after t

Running Runnablc Sleeping


Relinquishing control using sleepl) method
3. It has been told to wait until some cvent occurs. This is cdone using the wait( )
method. The thread can be scheduled to run again using the notify( ) method.
wait

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

to-java, lang, Exception


t-java.lar1g.lnterruptedException
Throw:. whn a thread is waiting, sleeping, or otherwise paused for a long
ime and another thread interrupts it using the interrupt method in class Thread.

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

public static void main(String args[)


ligetting reference to the current thread.
Thrcad t=Thread.currentThread();
lldetemining if the thread is still running.
System.out.println(" Detecting state of the running thread: "+t.isAliven :
ldescribing the thread.
IIOutput format: (namne of the thread, priority, name of
/* thread group: it is a data 1hread groyp]
structure that controls the state ofa
collection of threads as a whole
System.out. println(" Current thread before renaming: "+t};
llobtain a thread priority.
System.out.printh(" Priority of the current thread: "+t.getPriority();
llchange the internal name of the thread
L.setName("My Thread");
l/obtain the name of the thread
System.out.printh(" Current thread after renaming: "+t.ge Nare());
try

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

A thread can be created by instantiating an object of type Thread. There tivo


mechanisms toaccomplish the above, namely,
o By implementing Runnable interface.
o By extending Thread.
IMPLEMENTING RUNNABLE: To implement Runnable, we must only inpleinent the
method called run(), which is declared as follows:
public void run()
inside this method we have to he code that constitute the nevw thread. It is the entry point for
another, concurrent thread of execution within our program. This thread will end when rn()
retuins. After declaring a class that implements Runnable interface. we shonld initiate the
object of type Thread using one of its several constructors like:
Thread(Runnable threadOb, String nteadName)
In this constructor, threadOb is an instance of aclass that implements the Rurmghle interface.
This defines where execution of the thread will begin. The name of the new thrcad is
specified by threadName. After the new thread is created, we have to start the thrcad using
start()method of Thread class, as it will not start autonatically.
PROGRAM 2
/* Create a new thread */
class NewThrcad implements Runnable

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");

System.out.println(" Existing from cihild thread");

class ThreadDriver

public static void main(String args))


{
llcreate a new thread
new NewThrea1);
try

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");

System.out.prin1 In(" Existing from main thread"):


j* OUTPUT:
Child thread: Thread[Domo
Main j= 5 Thread,5,main]
Child i= 5
Child i= 4
Main i= 4
Child i= 3
Child i= 2
Main i= 3
Child /= 1
Existing from child thread
Main i= 2
Main i= 1
Existing from main thread
In multithread program, often the main thread must be the last thread to finish running. In
fact, for some older JVMs, if the main thread finishes before a child thread has completed,
then the Java run time system may "hang". Hence for older compatibility, child thread should
sleep for less time with respect to its parent's leeping period. This causes the child thread to
terminate earlier than the main thread.

EXTENDING THREAD CLASS:


The second way to create a thread is to create a new class that extends Thread, and
then to create an instance of that class. The exte3nding class must override the run() method.
Here is the same program as above, rewritten to extend Thread:
PROGRAM 3
/* Create a new threadby extending Thread */
class NewThread extends Thread

NewThread()
l/createa new second thread
super("DomoThread");
System.out.println(" Child thread: "+this);
I/start the thread
start);

public void run()

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

public static void nain(String args[)


llcreate a new thread
new NewThread():
try
{
for(int i=5;i>0:i--)
Systern.out.println(" Main i= "+i):
Thread.sleep(1000);
catch(Interr1pted
{ Exception e)
System.out.printin(" Main thread interrupted");
System.out.printin(" Existing from main thread");
j*
OUTPUT: Same as above
N.B. if we are not.
simply to implementoveriding
Runnable
any of Thread's other
methods, it is probably the best
interface. /Tl oaaut auoften cat .
appre
CREATING MUT]PLE THREAD: /u ols
PROGRAM 4 Morteover that if the class has alne
class NewThread Xtemded from amothe class the
to imþle nemt
inpleir.ents Runnable Ruy ble imtertf
String name;
Thread t;
NewThread(String n)
name=n;
t=new Thread(this,n);
System.out.println"New Thread: "+t);
t.start();
public void run()

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

public static voidmain(String args[))


new NewThread("Fist");
neiw NewThréad("Second");
new NewThread("Third");

try

l/wait for other threads to end


Thread.sleep(10000):
catch(InterruptedException e)
System.out.printn(" main thread interrupted");
System.out. print in(" Existing from main thread"):
}

/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 C extends Thread Catch ( Thread Death td)

public void run() S.0.P("This thread is


Ifor (imt k=j00, K<=500; k4 z100) goingto dieat
forfintk-ttms6;k+to0 throw tdy
System.out.printIn("t Thread C:k="+k);
try
400
if(k=)
sleep(1000); S.0.P( "Exit from thread
8 );
catch(InterruptedException e)
{
System.out.printin(" Exception from thread C"):
System.out.printIn(" Exit from thread C);

class ThreadDriver3

public static void main(String[ args)


AthObl=new A);
BthOb2=new B);
CthOb3-=new C);

System.out.printn(" Starting Thread A");


thObl.start();
System.out.println(" Starting Thread B");
thOb2.start();
System.out.printn(" Starting Thread C"):
thOb3.start();
System.out.printin(" End of main tlhread");
OUT PUT:.

QUTPUT: Startimg Thrcea d A


Starting Thrcad 4 Starting Thrtead B
Starting Thread B stontimg Thread e
Starting Thread End of main
hread B::j l)
End of main thread thres
Thrcea dA
Thread Ck=/130 Thread a
Thread A:.i1
Thread B:j 20 Thrread:
Thread B
Thrcad C::- 200 this Thread
Thread A:f- 2 is 90
Thread B/ 30
Thread ::k= 30)
Thread A:j-3 Theead eik
Thtead B:j=40 Thtead C:k
Thread C:;k= 400
Thread A:i 4 ThrreadC
Thread B:ja S0
Thrgad'C::k:= 506
Thnead Ai:
Thyead A:ij: 5 Thread A::
Exit frofn thread it Thrtead A:
Exit fpm thread Thread A::
Exit ffom thread */ Exit fromm Thread
Thread Ci:
Stopping a th:ead Exit from Thtea
A thread dies whea on: Tf the following things
happens:
The run() methTd called by the Thread returns.
An exception is thrn that causes the run() method to be exited.
The stop0 metod sf the Thread is called.
The stop) method of the Thread class works by
run() method of it e tuead. Normally, you should notthrowing
a ThreadDeath object in
catch
statement. If you n2ed to catch ThreadDeath objects to detect ThreadlDeatlh objects in a
that a Thread is abeut to
the try statement that ca tches ThreadDeath objects should rethrow then.
When an obje1 (T.1readDeath or otherwise) is thrown out of the run() method or
Thread, the uncauyn1Ex«eption() method of the ThrcadGroup for that lhrcad is calkad.
thrown object is an instance of the Thread Death class, the thrcad dics, and the thrown 0L
is ignored. Otherw.se, if :he throwm objcct is of any other class,
thrown object's priun`tackTrace() method, the thread dies, and uncauyitException) call
the thrown object is gt
In either case, if there are other nondaemon threads running in the
system, tle CU
program continues to run.

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.

USING isAlive() AND join():


Using sleep() method we have prevented death of the main thread, 8o that all child
threads terminate prior to the mafn thread. But it is not a satisfactory solution. Thread
provides two means by which we can determine whether a thread has finished.
1. final Boolean isAlive() - this method is defined by Thread and returns true
if the thread upon which it is called is still running. It returns false
otherwise.
2. final void join() throws InterruptedException - this method waits until the
thread on which it is called terminates. Its name concs from the concept of
the calling thread waiting until the speciffed thread joins it.
PROGRAM 6

class NewThread implements Runnable

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

for(int i-5; Þ0; i-)


System.out.printin("t"+name+"::i= "+i);
Thread.sleep(1000);
}
catch(lnterruptedException e)
System.out.prinn(name-+" interrupted");
System.out.printin(name+" terminating");
class ThreadDriv2r4
public static void main(String args[D)
NewThread obl=ew NewThread("First");
NewThread b2-1ew NewThread("Second");
NewThread cb3=rew NewThread("Third");
System.ooutut..ppririntln
System. ntin(""Status
Status of Firstthread: "+
obl.t.isAive));
of Second thread: "+
System.out.println" Status of Third thread: "+ ob2.t.isAlive():
ob3.t.isAlive());
try

System.out.println(" Waiting for threads to finish");


obl.t.join();
ob2.t.join);
}ob3.t.join();
catch(InterruptedException
{ e)
System.out.print.n(" Main thread interrupted");
Systeerm.m.ooutut..ppr:r1tr tn("
Syst in(" Status
Status of First thread: "+t
of Second obl.t.isAlive()):
System.out.prir tln(' Status ofThird thread:
thread: "+ ob2.t. isAlive)):
"+
System.out.printIn(" Main thread ob3.t.isAlive()):
terminating");
* QUTPUT:
New thread: First
New thread: Second
New thread: Third
Second::i=5
First::i= $
VStatus of First thread: true
Third::i= 5
Status of Second thread: true
Status of Third thread: true
the o/p at P/e.
Waiting for threas to finish See be differc.
First:i= 4
Third::i= 4
Second:i= 4
Second::i=3
Third:i= 3
First::i=3
Second::i= 2
Third::i=2
First::i= 2
Third:: 1
Second::i= 1
First:1
First terminating
Tbird terminating
Second terminating
Statusof First thread: false
Status of Second thread: false
Status of Third thread: false
Main thread terminating
THREAD PRIORITY:
Thread priority are used by the thrcad scheduler to decide when cach thread should be
allowed to run. In theory, higher-priority thrcads get more CPU timc thar: lower-priority
thread. In practice, the amount of CPUtime that a thread gets otten depends on several
factors besides its priority. Ahigher-priority thread can also preempt a lower-priority one.
Intheory, threads of equal priority should get equal access to the CPU. Bu. we need to
be careful because Java is designed to work in a wide range of environment. Some of these
enviromments implement multitasking fundarnentally diferently than others. For safety,
threads that share the sarme priority should yield control once in a whilc. This ensures that all
threads have a chance to run under a nonpreermptive operating system. In practice, even in
nonpreermptive environments, riost threads still get a chance to run, because most threads
inevitably encounter some blocking situation, such as wating for /O. When this happens, the
blocked thread is suspended and other threads can run. But, if we want smovth multlhreaded
execution, we should not rely on this. Also, some types of tasks are CPU-intensive. Such
thrcads dominate th: CPU. For these types of thrcads, we should
so that other tha:ads can run. yield control
Java per nits us to set the priority of a thread using the
follows: se:Priority
The level is an ThrecdName.setPriority(int
integer value to which the
level)
final variables within thread. Namely, thrend priority is set. Thesc priorities are a
MIN PRIORITY 1
NORM PRIORITY=5
MAX_PRIORITY = 10
The level may asSsume one of these
constants or any value between l and 10, Mos ..
processes should use NORM_ PRIORITY,
network I/O and screen repainting should use plus
a
or minus 1. Background tasks
be very cautious when trying to value very near to the
use very high priority values. Thislower limit, W.)
purpose of using multithread. may defeat t
We can obtain the current
Thread: priority setting by calling the following metlod
ThreadName.getPriority(
Both of the methods )
mentioned above are final method of Thread class.
Implementation of Java may have
scheduling. Windows XP/98/NT/2000 version
The radically different behavior when it con
However other versions may work quite works, more or less, as we would a
we have threads that are
relying on
differently. Most of the
inconsistencies arise
CPU time. The safest way to preemptive behavior, instead of
threads that voluntarily give upobtain predictable, cross-platform cooperatively
behavior with
givi
Java is
control of the CPU.
PROGRAM 7

Objectives of the following


program: Its output illustrates the effect of
priority to athrevd. TT be noted,
thread Bhas pree1pted it and startedalthough the thread A started first, theassigning Ë
higher priù
has been assigned the printing the output first.
is the last to highest Immediately,
priority takes control over the other the thread Cl
com:l?te. two threads. The thres
class A extends Thead

public void run()


{
Syst
for(intem.i-1;
out.pi<-4;
rintlnit+)(" **thread-A started (WITHIN RUNO)");
System.out.println(" thread A::i="+ i);
System.out.println(" Exit from thread A");
class B extends Thread
public void run()

System.out.println(" **thread-B started (WITHIN RUN))");


forlint j=10jc=40gj+=100)’ for(intj =108, i <:400; j+ =109)
System.out.printin(" thread B:j= "+):
System.out.printIn(" Exit from thread B");

class C extends Thread

public void run)


System.out.printhn(" **thread-C started (WITHIN RUN())"):
for(int k=l00; k<=400; k+=100)
{
System.out.println(" thread C::k= "+ k);
System.out.printin(" Exit from thread C");

class ThreadDriver5

public static void main(String] args)


A threadA=new A():
BthreadB-new B);
C thread C=new CÇ;

threadC.setPriority(Thread. MAX _PRIORITY);


threadB.setPriority(threadA.getPriority)+1);
threadA.setPriority(Thread. MIN PRIORITY);

System.out.printin(" Thread Astarted");


threadA.start();
System.out.printin(" Thread Bstarted");
threadB.start();
System.out.println(" Thread C siarted");
thread C.start():
try
System.out.printin(" Waiting for tlrcads tinish"):
threadA.join();
thrcadB.join();
threadC.join);
catcSysth(Ineerm.rouutpt.epdExcept ionc)
rintin(" Main thread interrupted");
System.out.println(" Ernd of main thread'"):
OUTPUT;
Thread Astarted
Thread Bstarted
**thread-B
thread B:j= started
10 (WITHIN RUNO)
thread B::j= 20
thread B:j= 30
thread B::j= 40
Thread Cstarted
Exit fron thread B
**thread-C started (WITHIN RUNØ)
**thread-A
thread C::k= started
100 (WITHIN RUNO)
Waiting for
thread C:k=threads
200 to finish
thread C:k= 300
thread C::k= 400
Exit fromn thread C
thread A:i= 1
thread A::i=2
thread A:i=3
thread A::=4
Exit from thread' A !
Endof main thread */
PROGRAM 8
||
Demonstrate
class threaa
clicker implementsproperties
Runnable
int click--0;
Thread t;
public h0olean runing-truc;
clicker(int p)
{
t=new Thread(this);
t.setPriority(p);
public void run()
while(running)
click++;
}
}
voidstop)
running-false;
void start)
t.start();

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");

System.out.println(" Low-priority thread: "+ lo.click);


System.out.printIn(" High-priority thread: "+ hi.click);

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

votd cal(Strìng msg)


System.out.print(" ["+msg);
try

Thread.sleep(1000);
catch(InterruptedException e)
System.out.printin(" Iterrupted from call( )");
System.out,printin(" ]");

class Caller implements Runnable


String ms8;
Callme target;
Thread t;
Caller(Callme targ, String s)
target-targ;
msg-s;
t=new Thread(this);
t.start();
public void run()
target.call(msg);
class Synch
public static void main(Stringl] args)
Callme tt-new Callme);
Caller obl=new Caller(tt,"Jayanta");
Caller ob2-new Caller(tt,"Bishnu");
Caller ob3-ncw Caller(tt,"'Sen");
try
{
obl.t.join();
ob2.t.join();
ob3.t.join();
catch(InterruptedException e)
System.out. prirtn(" Interrupted from main()");

/* OUTPUT:
CAjprglthread>jav[.
[Jayanta
Synch
[Bishnu Ser ]
[

*/

Inference ofthe aboe


program: Desired Output,
[Jayanta )
[Bishnu ]
[Sen ]
But the result of the program
mixed-up output af the three message strings because by calli
sleep(), the call() method allows
all three threads from calling the execution to switch to another thread and nothing to s
known as arac conditiop, becausesame method, on the same object, at the
the three methods are racing each same time. Thi
method. In most situations, arace condition is other to
cannot be sure when the context switch subtler and less predictable, completel
because
willoccur. This can cause the
one time and wrong next time, program to runNE
To fix the above problem we must
serialize access to the corresponding method (cal
method). That is, we must restrict its access to only one thread at a tine.
using twO mechanisms: This can be do
1. Using synchronized
class Callme!
modifier for the call( ) method as,
synchronized void call(String msg){
2. The above
synchronize access to mechanism
is not effective in all
object ofaclass that was situations. Such as, when we want to
not designed for
class does not use
vender and we don'tsynchronized method, Or when the class ismultithreaded access i.c. the
have access to the source code. designcd by a third party
appropriate method
calls to the method within
Thus,
the class. Now we should use we can't add synchronized to the
defned by this class inside a the second mechanism, simply put
form of the synchronized block. Here is the general
synchrtnized statement:
synchronil statemnts
zed(obi:c){to be
} Here, ot ject is a synchronized.
block ensures that t. call to a reference to the object being synchronized. A
thread has successtully ntered member of object occurs only aftersynchronized
method that is a
previous Caller class. object's monitor. Hence the modified run( ) the curret
method of the
IIsynchronized calls to call()
public void run( )
synchronzed(target)
target.call(9;
ed
} Here, she call( )method is not
synchronized statement 0s used inside Caller's run()modified by synchronized. Instead, the
method get desired result.
to

You might also like