Thread model in java

2,306 views 63 slides Nov 01, 2019
Slide 1
Slide 1 of 63
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63

About This Presentation

Powerpoint Presentation


Slide Content

1

THREADS
A Process is a program in execution.
Two or more processes are running
concurrently in a computer is called
multitasking.
Java provides support for multithreading.
Multithreading threading environment , tasks
are known as threads.
Threads share the same address space and
cooperatively share the same heavy weight
process.
2

THREADS
A Process is a program in execution.
Two or more processes are running
concurrently in a computer is called
multitasking.
Java provides support for multithreading.
Multithreading threading environment , tasks
are known as threads.
Threads share the same address space and
cooperatively share the same heavy weight
process.
3

Definition:
 A thread is a line of execution. It is the
smallest unit of code that is dispatched by
the scheduler. Thus a process can contain
multiple threads to execute its different
sections. This is called multithreading.
Single threaded process: A process is made
up of one thread is known as single threaded
process.
Multithreaded Process: A process that
creates two or more threadsis called a
multithreaded process.
4

A multithreaded program contains two or
more parts that can run concurrently.
Each part of such a program is called a
thread, and each thread defines a separate
path of execution.
Multithreading is a specialized form of
multitasking.
Many problems solved concurrently.
5

Improved performance
Minimized system resource usage
Simultaneous access to multiple applications
Program structure simplification
Types of multitasking:
Multitasking is theability to execute
more than one task at the same. It can
be divided into two categories:
process-based
thread-based
6

7

Threads exist in several states. They
are:
Newborn state
Runnable state
Running state
Blocked state
Dead state
A Thread is always in one of these five
states.
8

 Whenwecreateathreadobject,the
threadisbornandissaidtobeinnewborn
state.Atthisstate,wecandoonlyoneof
thefollowingthings:
(i) Schedule it for running using start() method
(ii) Kill it using stop() method
9

10

 Itmeansthethreadisreadyfor
executionandiswaitingfortheavailability
oftheprocessor.
 Thethreadhasjoinedthequeueof
threadsthatarewaitingforexecution.
 Ifallthreadshaveequalpriority,then
theyaregiventimeslotsforexecutionin
roundrobinfashion.
 Thethreadthatrelinquishescontrol
(yield)joinsthequeueattheendandagain
waitsforitsturn.Thisprocessofassigning
timetothreadsisknownastime-slicing.
11

12

Runningmeansthattheprocessorhasgiven
itstimetothethreadforitsexecution.
Thethreadrunsuntilitrelinquishescontrol
onitsownoritispreemptedbyahigher
prioritythread.
Arunningthreadmayrelinquishitscontrol
inoneofthefollowingsituations:
13

14

 Athreadissaidtobeblockedwhenitis
preventedfromenteringintotherunnable
stateandsubsequentlytherunningstate.
 Thishappenswhenthethreadis
suspended,sleeping,orwaitinginorderto
satisfycertainrequirements.
15

Arunningthreadendsitslifewhenithas
completedexecutingitsrun()methodorwe
cankillitbysendingthestopmessage.
16

Start()-Thestartmethodstartsexecution
oftheinvokingobject.Itcanthrowan
IllegalThreadStateExceptionifthethread
wasalreadystarted.
Stop()–Thismethodterminatestheinvoking
object.
Suspend()–Themethodsuspendsthe
invokingobject.Thethreadwillbecome
runnableagainifitgetstheresume()
method.
Sleep()–Thismethodsuspendsexecutionof
theexecutingthreadforthespecified
numberofmilliseconds.Itcanthrowan
InterruptedException. 17
A running thread ends its life when it has completed executing its run() method or we can kill it by sending the stop message.

Thesyntax
Publicstaticvoidsleep(longms)
Thefollowingstatementcansuspend
executionoftheexecutingthreadforthe
specifiednumberofmillisecondsplus
nanoseconds.
Publicstaticvoidsleep(longms,intns)
Resume()–Theresume()methodrestartsthe
suspendedthreadatthepointatwhichit
washalted.Theresume()methodiscalledby
somethreadoutsidethesuspendedone,
thereisaseparateclasscalledResumed
whichdoesjustthat.
18

19

WhenaJavaprogramstartsup,onethread
beginsrunningimmediatelycalledthemain
threadoftheprogram.
ItcanbecontrolledthroughaThreadobject,
currentThread(),whichisapublicstatic
memberofThread.Itsgeneralformis:
staticThreadcurrentThread()
Itreturnsareferencetothethreadinwhichit
iscalled.
20

class CurrentThreadDemo {
public static void main(String args[ ])
{
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
// change the name of the thread
t.setName("My Thread");
System.out.println("After name change: " + t);
21

try {
for(int n = 5; n > 0; n--) {
System.out.println(n);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted");
}
} }
22

Current thread: Thread[main,5,main]
After name change:
Thread[My Thread,5,main]
5
4
3
2
1
23

Itisusedasanargumenttoprintln().This
displays,inorder:
thenameofthethread,
itspriority,and
thenameofitsgroup.
Bydefault,thenameofthemainthread
ismain.Itspriorityis5,whichisthe
defaultvalue,andmainisalsothename
ofthegroupofthreadstowhichthis
threadbelongs.
24

1. sleep( ) :
It causes the thread from which it is called
to suspend execution for the specified period
of milliseconds and also in nanoseconds.
static void sleep(long milliseconds) throws
InterruptedException
static void sleep(long milliseconds, int
nanoseconds) throws InterruptedException
2. setName( ):
To set the name of a thread.
final void setName(String threadName)
25

3. getName( ):
To obtain the name of a thread
final String getName( )
threadNamespecifiesthenameofthe
thread.
TheThreadclassdefinesseveralmethods
thathelpmanagethreads.
26

Method Meaning
getName() Obtain a thread’s
name.
setName(String) Sets the thread name
getPriority() Obtain a thread’s
priority.
isAlive() Determine if a thread
is still running.
27

Join() -Wait for a thread to
terminate.
run -Entry point for the thread.
sleep -Suspend a thread for a
period of time (ms).
start -Start a thread by calling its
run method.
28

activeCount()-Returnsthecurrentnumber
ofactiveThreadsinthisThreadGroup.
ToString() -Returns the string
representationoftheThread,includingthe
thread’sname,priorityandthreadgroup.
currentThread()-Returnsareferencetothe
currentlyexecutingThreadobject&isa
staticmethod.
29

A thread can be created in two ways;
Runnable interface.
Extend the Thread class, itself.
30

ToimplementRunnable,aclassneedonly
implementasinglemethodcalledrun(),
whichisdeclaredas:
publicvoidrun()
Then,instantiateanobjectoftypeThread
fromwithinthatclassusingconstructors.
Thread(Runnable threadOb, String
threadName)
Afterthenewthreadiscreated,itwillnot
startrunninguntilyoucallitsstart()
method,whichisdeclaredwithinThread.
voidstart()
31

class CreateThreadDemo
{
public static void main(String args[ ])
{
new NewThread(); // create a new thread
try
{
for(int k = 10; k > 6; k--){
System.out.println("Parent Thread: " + k);
Thread.sleep(1000);
}
}
32

catch (InterruptedException e)
{
System.out.println("Parent
Interrupted.");
}
System.out.println("Exiting Parent.");
}
}
33

class NewThread implements Runnable
{
Thread T;
NewThread() //a new, second thread
{
T = new Thread(this, "Creating Thread");
System.out.println("Thread of child: " +
T);
T.start(); // Start the thread
}
34

public void run() // Point of entry for the
second thread.
{
try
{
for(int j = 10; j > 6; j--){
System.out.println("Child Thread: " + j);
Thread.sleep(500);}
}
catch (InterruptedException e){
System.out.println("Child interrupted.");
}
System.out.println("Exiting Child.");
} }
35

Thread of child: Thread [Creating
Thread,5,main]
Parent Thread: 10
Child Thread: 10
Child Thread: 9
Parent Thread: 9
Child Thread: 8
Child Thread: 7
Parent Thread: 8
Exiting Child.
Parent Thread: 7
Exiting Parent.
36

class CreateThreadDemo
{
public static void main(String args[ ]){
new NewThread(); // create a new
thread
try
{
for(int k = 10; k > 6; k--) {
System.out.println("Parent Thread: " +k);
Thread.sleep(1000);
} }
37

catch (InterruptedException e)
{
System.out.println("Parent
Interrupted.");
}
System.out.println("Exiting Parent.");
}
}
38

class NewThread extends Thread
{
NewThread() //a new, second thread
{
super(“Demo Thread”);
System.out.println("Thread of child: “+this);
start(); // Start the thread
}
39

public void run() // Point of entry for the
second thread.
{
try
{
for(int j = 10; j > 6; j--)
{
System.out.println("Child Thread: " + j);
Thread.sleep(500);
}
}
40

catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting Child.");
}
}
41

To determine whether a thread has finished.
final boolean isAlive( )
It returns true if the thread upon which it is
called is still running, otherwise returns
false.
The method used to wait for a thread to
finish is called join( ),
final void join( ) throws
InterruptedException
This method waits until the thread on which
it is called terminates.
42

class NewThread implements Runnable
{
String name; // name of thread
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
43

public void run()
{
try {
for(int i = 3; i > 0; i--)
{
System.out.println(name + ": " + i)
Thread.sleep(1000);
}
}
44

catch (InterruptedException e)
{
System.out.println(name +
"Interrupted"); }
System.out.println(name + "exiting.");
}
}
class MultiThreadDemojoin {
public static void main(String args[])
{
NewThread ob1=new NewThread("One");
NewThread ob2=new NewThread("Two");
NewThread ob3=new NewThread("Three");
45

System.out.println("Thread 1 is
alive:"+ob1.t.isAlive());
System.out.println("Thread 2 is
alive:"+ob2.t.isAlive());
System.out.println("Thread 3 is
alive:"+ob3.t.isAlive());
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
46

catch (InterruptedExceptione)
{
System.out.println("Main thread
Interrupted"); }
System.out.println("Thread 1 is
alive:"+ob1.t.isAlive());
System.out.println("Thread 2 is
alive:"+ob2.t.isAlive());
System.out.println("Thread 3 is
alive:"+ob3.t.isAlive());
System.out.println("Main thread
Exiting");
}
}

47

New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 3
Two: 3
Thread 1 is alive:true
Thread 2 is alive:true
Thread 3 is alive:true
Three: 3
One: 2
Two: 2
Three: 2
48

Three: 1
One: 1
Two: 1
Three exiting.
One exiting.
Two exiting.
Thread 1 is alive: false
Thread 2 is alive: false
Thread 3 is alive: false
Main thread Exiting
49

Threadprioritiesareusedbythethread
schedulertodecidewheneachthreadshould
beallowedtorun.
Intheory,higher-prioritythreadsgetmore
CPUtimethanlowerprioritythreads.
Inpractice,theamountofCPUtimethata
threadgetsoftendependsonseveralfactors
besidesitspriority.
Tosetathread’spriority,usethesetPriority(
)method,whichisamemberofThread.This
isitsgeneralform:
 final void setPriority(int level)
50

Here, level specifies the new priority setting
for the calling thread.
The value of level must be within the range
MIN_PRIORITY and MAX_PRIORITY.
• MIN_PRIORITY =1
• MAX_PRIORITY = 10
• NORM_PRIORITY = 5 (default priority)
51

class Counter implements Runnable
{
Thread thread;
intcounter = 0;
volatile booleangoflag; // volatile –its value
can be changed by another thread
public Counter(intp)
{
thread = new Thread(this);
thread.setPriority(p);
}
52

public void start()
{ goflag= true;
thread.start();
}
public void run()
{ while (goflag)
counter++;
}
public void end()
{ goflag= false;
}
}
53

class PriorityDemo{
public static void main(String args[])
{
Counter thread1= new Counter
(Thread.NORM_PRIORITY+ 2);
Counter thread2 = new Counter
(Thread.NORM_PRIORITY+ 1);
Counter thread3 = new Counter
(Thread.NORM_PRIORITY-1);
Counter thread4 = new Counter
(Thread.NORM_PRIORITY-2);
54

thread1.start();
thread2.start();
thread3.start();
thread4.start();
try { Thread.sleep(5000); }
catch (InterruptedExceptione) {}
thread1.end();
thread2.end();
thread3.end();
thread4.end();
55

System.out.println("Thread 1 counted: " +
thread1.counter);
System.out.println("Thread 2 counted: " +
thread2.counter);
System.out.println("Thread 3 counted: " +
thread3.counter);
System.out.println("Thread 4 counted: " +
thread4.counter);
} }
Output:
Thread 1 counted: 145565315
Thread 2 counted: 123477095
Thread 3 counted: 6936384
Thread 4 counted: 6057269
56

Whentwoormorethreadsneedaccesstoa
sharedresource,theyneedsomewayto
ensurethattheresourcewillbeusedbyonly
onethreadatatime.Theprocessbywhich
thisisachievediscalledsynchronization.
Keytosynchronizationistheconceptofthe
monitoralsocalledasemaphore.
Amonitorisanobjectthatisusedasa
mutuallyexclusivelock,ormutex.
57

Onlyonethreadcanownamonitorata
giventime.
Whenathreadacquiresalock,itissaidto
haveenteredthemonitor.
Allotherthreadsattemptingtoenterthe
lockedmonitorwillbesuspendeduntilthe
firstthreadexitsthemonitor.Theseother
threadsaresaidtobewaitingforthe
monitor.
58

class SynchronizeDemo1
{
public static void main(String args[ ])
{
Shared shared= new Shared();
CustomThreadthread1 = new
CustomThread(shared, "one");
CustomThreadthread2 = new
CustomThread(shared, "two");
CustomThreadthread3 = new
CustomThread(shared, "three");
CustomThreadthread4 = new
CustomThread(shared, "four");
59

try
{
thread1.join();
thread2.join();
thread3.join();
thread4.join();
}
catch(InterruptedExceptione) { }
}
}
60

class CustomThreadextends Thread {
Shared shared;
public CustomThread(Shared shared, String
string) {
super(string);
this.shared= shared;
start(); }
public void run()
{
synchronized(shared)
{
shared.doWork(Thread.currentThread().getNa
me()); }
} }
61

class Shared{
void doWork(String string) {
System.out.println("Starting " + string);
try {
Thread.sleep((long) (Math.random() * 500));
}
catch (InterruptedExceptione) { }
System.out.println("Ending " + string);
}
62

Starting one
Ending one
Starting two
Ending two
Starting three
Ending three
Starting four
Ending four deprecate
63