Multithreading and Multiprocessing in Amity School of Engineering & Technology

 
Multithreading
 
1
 
Agenda
 
Multiprocessing
Type of Multiprocessing
What is Thread
Type of Thread
Multithreading
Thread Life Cycle
Multithreading Example
Advantages of Multithreading
 
What is Multiprocessing
 
The process of using the entire CPU of the
computer and being capable to execute
more then two processes or computational
jobs at a time is defined as
multiprocessing.
 
Type of Multiprocessing
 
There are two type of Multiprocessing in java.
1) Process-Based Multiprocessing
2) Thread Based Multiprocessing
Multiprocessing
Thread Based
Process Based
 
 
What is Thread(Separate flow of
Execution)
 
A thread is an individual, light weight, and a
smallest unit of a given process. There are
multiple thread in a single process and each
thread is independent of the other.
 
 As shown in figure ,a thread is executed inside the process .There is a context switching
 between the threads. There can be multiple processes inside the OS and one process
 can have multiple threads.
 
 
Type of Thread
 
1. User Thread
2. Daemon Thread
User threads are high-priority threads. The
JVM will wait for any user thread to
complete its task before terminating it. On
the other hand, daemon threads are low-
priority threads whose only role is to
provide services to user threads
 
Use of Daemon Thread
 
Daemon threads are useful for background
supporting tasks such as garbage collection,
releasing memory of unused objects and
removing unwanted entries from the cache. Most
of the JVM threads are daemon threads.
 
 
Multithreading
 
Multithreading is a Java feature that allows
concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part
of such program is called a thread. So, threads are
light-weight processes within a process.
Threads can be created by using two mechanisms :
1.
Extending the Thread class
2.
Implementing the Runnable Interface
 
Cont..
 
Advantages of multithread
 
The users are not blocked because threads are
independent, and we can perform multiple
operations at times
As such the threads are independent, the other
threads won’t get affected if one thread meets an
exception.
 
Thread Life Cycle in Java
 
 
New state
 
Before calling the start() method on the newly
created thread instance, the thread is in a “new
state”.
I
n
 
t
h
i
s
 
p
h
a
s
e
,
 
t
h
e
 
t
h
r
e
a
d
 
i
s
 
c
r
e
a
t
e
d
 
u
s
i
n
g
 
c
l
a
s
s
T
h
r
e
a
d
 
c
l
a
s
s
.
 
I
t
 
r
e
m
a
i
n
s
 
i
n
 
t
h
i
s
 
s
t
a
t
e
 
t
i
l
l
 
t
h
e
p
r
o
g
r
a
m
 
s
t
a
r
t
s
 
t
h
e
 
t
h
r
e
a
d
.
 
I
t
 
i
s
 
a
l
s
o
 
k
n
o
w
n
 
a
s
 
b
o
r
n
t
h
r
e
a
d
.
 
 
Runnable state
 
The thread is in a “runnable state” after calling the
start() method, but it has not been selected as the
running thread by the thread scheduler.
In this phase, the instance of the thread is invoked
with a start method. The thread control is given to
scheduler to finish the execution. It depends on
the scheduler, whether to run the thread.
 
Running state
 
If the thread scheduler has selected it as a
running thread, it is on the “running state”.
A thread will only execute its task when it is
on the “running state”.
 
Waiting state
 
When a thread is still alive but not eligible to run,
then the thread is in the “waiting state”. A thread
can move from “running state” to “waiting state”
by certain conditions ex: sleep(), wait(). Same as
that a thread can move from “waiting state” to
“runnable state” by certain conditions ex: notify(),
interrupt().
 
Death state or Terminate
 
When a thread completes all of the tasks
assigned to it, or when its run() method
exits, it will become a dead thread.
 
Example
 
package demotest;
public class GuruThread {
public static void main(String[] args)
 {
      System.out.println("Single Thread");
 }
}
 
Creating Threads
 
We can create threads in two different
ways, They are
1.
Extend Thread class
2.
Implement Runnable interface
 
T
he behaviour of the thread object will be
the same in both ways.
 
Method 1-
Extend thread class
 
public
 
class
 
Mythread
 
extends
 
Thread
{
@Override
public
 
void
 
run
(){
             S
ystem
.
out
.
println(
"Hi!! This is from child
thread"
);
            }
}
public
 
class
 
Application
 {
public
 
static
 
void
 
main
(
String
[] 
args
) {
Mythread
 mythread
=new
 
Mythread
();
mythread
.
start();
 }}
 
What is start() method and
run() method?
 
We override the run() method and specify
the tasks we want to assign to the newly
created thread. Then we call the start()
method on the thread instance that we
created. Please keep in mind that the
start() method is belongs to “Thread” class,
and it will call the run() method internally.
 
What happens if we didn’t
override the run() Method?
 
A thread will be created, but it does nothing and then
it will go to death state.
public
 
class
 
Mythread
 
extends
 
Thread
{
//we didn't override run() method here
 }
public
 
class
 
Application
 {
       public
 
static
 
void
 
main
(
String
[] 
args
) {
             
Mythread
 mythread
=new
 
Mythread
();
             
mythread
.
start();
        }
}
 
E
x
p
l
a
n
a
t
i
o
n
 
When we invoke the start() method, A thread will be
created. start() method will invoke the run() method
internally. Then JVM checks whether the child class
contains a run() method. If yes then child class’s run
method will be executed. If not JVM will execute the
parent (Thread) class’s run() method. In Java
“Thread” class’s run() method doesn’t contain any
tasks in its body. Therefore if we didn’t override the
run() method, the Thread class’s run() method will be
invoked and it does nothing
.
 
Can we overload the run()
method?
 
public
 
class
 
Mythread
 
extends
 
Thread
{
     @Override
     public
 
void
 
run
(){
             S
ystem
.
out
.
println(
"Hi!! This is from child thread default run method"
);
            }
      public
 
void
 
run
(String name){
             S
ystem
.
out
.
println(
"Hi!! This is from child thread's over loaded
method"
);
            }
 
        }
public
 
class
 
Application
 {
           public
 
static
 
void
 
main
(
String
[] 
args
) {
           Mythread
 mythread
=new
 
Mythread
();
           mythread
.
start();
 }}
 
E
x
p
l
a
n
a
t
i
o
n
 
Yes we can overload the run() method. but
start() method will only invoke run() method
which has no arguments. Therefore the
overloaded run() method will not be
invoked by start() method
.
 
Can we invoke run() method
instead of start() method?
 
public
 
class
 
Mythread
 
extends
 
Thread
{
           @Override
           public
 
void
 
run
(){
             S
ystem
.
out
.
println(
“This method is executed by:“
                  
+Thread.currentThread.getName()
);
            }
}
public
 
class
 
Application
 {
               public
 
static
 
void
 
main
(
String
[] 
args
) {
               Mythread
 mythread
=new
 
Mythread
();
               //mythread
.
start();
               Mythread.run();
      }
}
 
E
x
p
l
a
n
a
t
i
o
n
 
W
e can invoke the run() method directly. but it
will not create a new child thread. Instead,
parent thread will execute the child thread
object’s run() method. This will be a typical
OOP method invoking.
 
C
an we override the start()
method?
 
public
 
class
 
Mythread
 
extends
 
Thread
{
@Override
public
 
void
 
run
(){
             S
ystem
.
out
.
println(
“This is run method”);
}
@Override
public
 
void
 
start
(){
             S
ystem
.
out
.
println(
“This is start method”);
}
 
}
public
 
class
 
Application
 {
          public
 
static
 
void
 
main
(
String
[] 
args
) {
         Mythread
 mythread
=new
 
Mythread
();
         mythread
.
start();
     }
}
 
Drawbacks of this way of Thread
C
reation
 
W
e know Java doesn’t support multiple
inheritances. In this way, Since user-created
class (Mythread) Inherits the characteristics
from “Thread class”, user-created class
(Mythread)can’t inherit another class.
 
Method 2: Implement the Runnable
Interface
 
To create a thread by runnable interface we must
create a class that implements runnable interface.
public
 
class
 
Rnblthread
 
implements
 
Runnable
{
@Override
     public
 
void
 
run
() {
       
System
.
out
.
println(
"Hi!! This is from a child thread
which is created
         by runnable interface"
);
       }
}
 
Cont..
 
After implementing the runnable interface we
can simply create the thread by creating a
thread object.
public
 
class
 
Application
 {
     public
 
static
 
void
 
main
(
String
[] 
args
) {
              Runnable
 r
=new
 
Rnblthread
();
              Thread
 mythread
=
 
new
 
Thread
(r);
              mythread
.
start();
            }
   }
 
 
Cont..
 
1.
N
E
W
 
 
a
 
n
e
w
l
y
 
c
r
e
a
t
e
d
 
t
h
r
e
a
d
 
t
h
a
t
 
h
a
s
 
n
o
t
 
y
e
t
s
t
a
r
t
e
d
 
t
h
e
 
e
x
e
c
u
t
i
o
n
2.
R
U
N
N
A
B
L
E
 
 
e
i
t
h
e
r
 
r
u
n
n
i
n
g
 
o
r
 
r
e
a
d
y
 
f
o
r
e
x
e
c
u
t
i
o
n
 
b
u
t
 
i
t
'
s
 
w
a
i
t
i
n
g
 
f
o
r
 
r
e
s
o
u
r
c
e
 
a
l
l
o
c
a
t
i
o
n
3.
B
L
O
C
K
E
D
 
 
w
a
i
t
i
n
g
 
t
o
 
a
c
q
u
i
r
e
 
a
 
m
o
n
i
t
o
r
 
l
o
c
k
 
t
o
e
n
t
e
r
 
o
r
 
r
e
-
e
n
t
e
r
 
a
 
s
y
n
c
h
r
o
n
i
z
e
d
 
b
l
o
c
k
/
m
e
t
h
o
d
4.
W
A
I
T
I
N
G
 
 
w
a
i
t
i
n
g
 
f
o
r
 
s
o
m
e
 
o
t
h
e
r
 
t
h
r
e
a
d
 
t
o
p
e
r
f
o
r
m
 
a
 
p
a
r
t
i
c
u
l
a
r
 
a
c
t
i
o
n
 
w
i
t
h
o
u
t
 
a
n
y
 
t
i
m
e
 
l
i
m
i
t
5.
T
I
M
E
D
_
W
A
I
T
I
N
G
 
 
w
a
i
t
i
n
g
 
f
o
r
 
s
o
m
e
 
o
t
h
e
r
 
t
h
r
e
a
d
t
o
 
p
e
r
f
o
r
m
 
a
 
s
p
e
c
i
f
i
c
 
a
c
t
i
o
n
 
f
o
r
 
a
 
s
p
e
c
i
f
i
e
d
 
New
 
R
u
n
n
a
b
l
e
 
r
u
n
n
a
b
l
e
 
=
 
n
e
w
 
N
e
w
S
t
a
t
e
(
)
;
T
h
r
e
a
d
 
t
 
=
 
n
e
w
 
T
h
r
e
a
d
(
r
u
n
n
a
b
l
e
)
;
L
o
g
.
i
n
f
o
(
t
.
g
e
t
S
t
a
t
e
(
)
)
;
 
Runnable
 
W
h
e
n
 
w
e
'
v
e
 
c
r
e
a
t
e
d
 
a
 
n
e
w
 
t
h
r
e
a
d
 
a
n
d
 
c
a
l
l
e
d
t
h
e
 
s
t
a
r
t
(
)
 
m
e
t
h
o
d
 
o
n
 
t
h
a
t
,
 
i
t
'
s
 
m
o
v
e
d
f
r
o
m
 
N
E
W
 
t
o
 
R
U
N
N
A
B
L
E
 
s
t
a
t
e
.
 
T
h
r
e
a
d
s
 
i
n
 
t
h
i
s
s
t
a
t
e
 
a
r
e
 
e
i
t
h
e
r
 
r
u
n
n
i
n
g
 
o
r
 
r
e
a
d
y
 
t
o
 
r
u
n
,
 
b
u
t
t
h
e
y
'
r
e
 
w
a
i
t
i
n
g
 
f
o
r
 
r
e
s
o
u
r
c
e
 
a
l
l
o
c
a
t
i
o
n
 
f
r
o
m
t
h
e
 
s
y
s
t
e
m
In a multi-threaded environment, the Thread-
Scheduler (which is part of JVM) allocates a
fixed amount of time to each thread. So it runs
for a particular amount of time, then relinquishes
the control to other 
RUNNABLE
 threads.
 
Example
 
R
u
n
n
a
b
l
e
 
r
u
n
n
a
b
l
e
 
=
 
n
e
w
 
N
e
w
S
t
a
t
e
(
)
;
T
h
r
e
a
d
 
t
 
=
 
n
e
w
 
T
h
r
e
a
d
(
r
u
n
n
a
b
l
e
)
;
t.start();
Log.info(t.getState());
 
Blocked
 
A
 
t
h
r
e
a
d
 
i
s
 
i
n
 
t
h
e
 
B
L
O
C
K
E
D
 
s
t
a
t
e
 
w
h
e
n
i
t
'
s
 
c
u
r
r
e
n
t
l
y
 
n
o
t
 
e
l
i
g
i
b
l
e
 
t
o
 
r
u
n
.
 
I
t
 
e
n
t
e
r
s
t
h
i
s
 
s
t
a
t
e
 
w
h
e
n
 
i
t
 
i
s
 
w
a
i
t
i
n
g
 
f
o
r
 
a
m
o
n
i
t
o
r
 
l
o
c
k
 
a
n
d
 
i
s
 
t
r
y
i
n
g
 
t
o
 
a
c
c
e
s
s
 
a
s
e
c
t
i
o
n
 
o
f
 
c
o
d
e
 
t
h
a
t
 
i
s
 
l
o
c
k
e
d
 
b
y
 
s
o
m
e
o
t
h
e
r
 
t
h
r
e
a
d
.
 
Example
 
i
m
p
o
r
t
 
j
a
v
a
.
u
t
i
l
.
l
o
g
g
i
n
g
.
L
o
g
M
a
n
a
g
e
r
;
I
m
p
o
o
r
t
 
j
a
v
a
.
u
t
i
l
.
l
o
g
g
i
n
g
.
L
o
g
g
e
r
;
p
u
b
l
i
c
 
c
l
a
s
s
 
B
l
o
c
k
e
d
S
t
a
t
e
 
{
p
u
b
l
i
c
 
s
t
a
t
i
c
 
v
o
i
d
 
m
a
i
n
(
S
t
r
i
n
g
[
]
 
a
r
g
s
)
 
t
h
r
o
w
s
 
I
n
t
e
r
r
u
p
t
e
d
E
x
c
e
p
t
i
o
n
 
{
 
 
T
h
r
e
a
d
 
t
1
 
=
 
n
e
w
 
T
h
r
e
a
d
(
n
e
w
 
D
e
m
o
T
h
r
e
a
d
B
(
)
)
;
 
 
T
h
r
e
a
d
 
t
2
 
=
 
n
e
w
 
T
h
r
e
a
d
(
n
e
w
 
D
e
m
o
T
h
r
e
a
d
B
(
)
)
;
  LogManager lgmngr=LogManager.getLogManager();
  Logger log=lgmngr.getLogger(Logger.GLOBAL_LOGGER_NAME);
  t1.start();
  t2.start();
  Thread.sleep(
1000
);
  log.info(String.valueOf(t2.getState()));
  System.exit(
0
); }
}
 
Example
 
class
 
DemoThreadB
 
implements
 
Runnable
 {
@Override
 
public
 
void
 
run
() {
     
commonResource();
   
}
public
 
static
 
synchronized
 
void
commonResource
() {
     while
(
true
) { 
// Infinite loop to mimic
heavy processing
 
// 't1' won't leave this
method
 
// when 't2' try to enter this
 } } }
 
Explanation
 
1.
We've created two different threads – 
t1
 and 
t2
2.
t1 
starts and enters the
synchronized 
commonResource() 
method; this means
that only one thread can access it; all other
subsequent threads that try to access this method will
be blocked from the further execution until the current
one will finish the processing
3.
When 
t1 
enters this method, it is kept in an infinite
while loop; this is just to imitate heavy processing so
that all other threads cannot enter this method
4.
Now when we start 
t2
, it tries to enter
the 
commonResource() 
method, which is already
being accessed by 
t1,
 thus, 
t2 
will be kept in
the 
BLOCKED
 state
 
L
i
s
t
 
o
f
 
C
o
m
m
o
n
l
y
 
U
s
e
d
 
T
h
r
e
a
d
 
c
l
a
s
s
C
o
n
s
t
r
u
c
t
o
r
s
.
 
Thread class has the following eight constructors.
T
h
r
e
a
d
(
)
:
 
I
t
 
c
r
e
a
t
e
s
 
a
 
T
h
r
e
a
d
 
o
b
j
e
c
t
 
w
i
t
h
 
a
 
d
e
f
a
u
l
t
 
n
a
m
e
.
T
h
r
e
a
d
(
S
t
r
i
n
g
 
n
a
m
e
)
:
 
I
t
 
c
r
e
a
t
e
s
 
a
 
T
h
r
e
a
d
 
o
b
j
e
c
t
 
w
i
t
h
 
a
 
n
a
m
e
 
t
h
a
t
t
h
e
 
n
a
m
e
 
a
r
g
u
m
e
n
t
 
s
p
e
c
i
f
i
e
s
.
T
h
r
e
a
d
 
(
R
u
n
n
a
b
l
e
 
r
)
:
 
T
h
i
s
 
m
e
t
h
o
d
 
c
o
n
s
t
r
u
c
t
s
 
T
h
r
e
a
d
 
w
i
t
h
 
a
p
a
r
a
m
e
t
e
r
 
o
f
 
t
h
e
 
R
u
n
n
a
b
l
e
 
o
b
j
e
c
t
 
t
h
a
t
 
d
e
f
i
n
e
s
 
t
h
e
 
r
u
n
(
)
 
m
e
t
h
o
d
.
T
h
r
e
a
d
 
(
R
u
n
n
a
b
l
e
 
r
,
 
S
t
r
i
n
g
 
n
a
m
e
)
:
 
T
h
i
s
 
m
e
t
h
o
d
 
c
r
e
a
t
e
s
 
T
h
r
e
a
d
w
i
t
h
 
a
 
n
a
m
e
 
a
n
d
 
a
 
R
u
n
n
a
b
l
e
 
o
b
j
e
c
t
 
p
a
r
a
m
e
t
e
r
 
t
o
 
s
e
t
 
t
h
e
 
r
u
n
(
)
m
e
t
h
o
d
.
T
h
r
e
a
d
(
T
h
r
e
a
d
G
r
o
u
p
 
g
r
o
u
p
,
 
R
u
n
n
a
b
l
e
 
t
a
r
g
e
t
)
:
 
I
t
 
c
r
e
a
t
e
s
 
a
T
h
r
e
a
d
 
o
b
j
e
c
t
 
w
i
t
h
 
a
 
R
u
n
n
a
b
l
e
 
o
b
j
e
c
t
 
a
n
d
 
t
h
e
 
g
r
o
u
p
 
t
o
 
w
h
i
c
h
 
i
t
b
e
l
o
n
g
s
.
 
T
h
r
e
a
d
 
(
T
h
r
e
a
d
G
r
o
u
p
 
g
r
o
u
p
,
 
R
u
n
n
a
b
l
e
 
t
a
r
g
e
t
,
S
t
r
i
n
g
 
n
a
m
e
)
:
 
I
t
 
c
r
e
a
t
e
s
 
T
h
r
e
a
d
 
o
b
j
e
c
t
 
w
i
t
h
 
a
R
u
n
n
a
b
l
e
 
o
b
j
e
c
t
 
t
h
a
t
 
d
e
f
i
n
e
s
 
t
h
e
 
r
u
n
(
)
 
m
e
t
h
o
d
,
s
p
e
c
i
f
i
e
d
 
n
a
m
e
 
a
s
 
i
t
s
 
n
a
m
e
 
a
n
d
 
t
h
e
 
T
h
r
e
a
d
 
o
b
j
e
c
t
b
e
l
o
n
g
s
 
t
o
 
t
h
e
 
T
h
r
e
a
d
G
r
o
u
p
 
r
e
f
e
r
r
e
d
 
t
o
 
b
y
 
t
h
e
 
g
r
o
u
p
.
T
h
r
e
a
d
(
T
h
r
e
a
d
G
r
o
u
p
 
g
r
o
u
p
,
 
S
t
r
i
n
g
 
n
a
m
e
)
:
 
I
t
c
r
e
a
t
e
s
 
a
 
t
h
r
e
a
d
 
t
h
a
t
 
h
a
s
 
t
h
e
 
s
p
e
c
i
f
i
e
d
 
n
a
m
e
 
a
n
d
a
s
s
o
c
i
a
t
e
s
 
t
o
 
t
h
e
 
T
h
r
e
a
d
G
r
o
u
p
 
g
i
v
e
n
 
a
s
 
t
h
e
 
f
i
r
s
t
p
a
r
a
m
e
t
e
r
.
T
h
r
e
a
d
(
T
h
r
e
a
d
G
r
o
u
p
 
g
r
o
u
p
,
 
R
u
n
n
a
b
l
e
 
t
a
r
g
e
t
,
S
t
r
i
n
g
 
n
a
m
e
,
 
l
o
n
g
 
s
t
a
c
k
S
i
z
e
)
:
 
t
h
i
s
 
c
o
n
s
t
r
u
c
t
o
r
s
p
e
c
i
f
i
e
s
 
t
h
e
 
T
h
r
e
a
d
G
r
o
u
p
 
p
a
r
a
m
e
t
e
r
,
 
t
h
e
 
s
i
z
e
 
o
f
 
t
h
e
t
h
r
e
a
d
s
 
m
e
t
h
o
d
-
c
a
l
l
 
s
t
a
c
k
.
 
C
o
m
m
o
n
l
y
 
u
s
e
d
 
m
e
t
h
o
d
s
 
o
f
T
h
r
e
a
d
 
c
l
a
s
s
 
1.
public void run():
 is used to perform action for a thread.
2.
public void start():
 starts the execution of the thread.JVM calls
the run() method on the thread.
3.
public void sleep(long miliseconds):
 Causes the currently
executing thread to sleep (temporarily cease execution) for the
specified number of milliseconds.
4.
public void join():
 waits for a thread to die.
5.
public void join(long miliseconds):
 waits for a thread to die for
the specified miliseconds.
6.
public int getPriority():
 returns the priority of the thread.
7.
public int setPriority(int priority):
 changes the priority of the
thread.
8.
public String getName():
 returns the name of the thread.
 
 
 
 
9. public void setName(String name):
 changes the name of the
thread.
10. public Thread currentThread():
 returns the reference of
currently executing thread.
11. public int getId():
 returns the id of the thread.
12. public Thread.State getState():
 returns the state of the
thread.
13. 
public boolean isAlive():
 tests if the thread is alive.
14. 
public void yield():
 causes the currently executing thread
object to temporarily pause and allow other threads to execute.
15. public void suspend():
 is used to suspend the
thread(depricated).
16. public void resume():
 is used to resume the suspended
thread(depricated).
17. public void stop():
 is used to stop the thread(depricated)
 
18. public boolean isDaemon():
 tests if the thread is a
daemon thread.
19. public void setDaemon(boolean b):
 marks the
thread as daemon or user thread.
20. public void interrupt():
 interrupts the thread.
21. public boolean isInterrupted():
 tests if the thread
has been interrupted.
22. public static boolean interrupted():
 tests if the
current thread has been interrupted.
 
T
h
r
e
a
d
 
E
x
a
m
p
l
e
 
b
y
 
i
m
p
l
e
m
e
n
t
i
n
g
R
u
n
n
a
b
l
e
 
i
n
t
e
r
f
a
c
e
 
class
 Multi3 
implements
 Runnable{
public
 
void
 run(){
System.out.println(
"thread is running..."
);
}
public
 
static
 
void
 main(String args[]){
Multi3 m1=
new
 Multi3();
Thread t1 =
new
 Thread(m1);   
// Using the constructor Thread(R
unnable r)
t1.start();
 }
}
 
Example getName()
 
p
u
b
l
i
c
 
c
l
a
s
s
 
M
y
T
h
r
e
a
d
1
{
// Main method
p
u
b
l
i
c
 
s
t
a
t
i
c
 
v
o
i
d
 
m
a
i
n
(
S
t
r
i
n
g
 
a
r
g
v
s
[
]
)
{
// creating an object of the Thread class using the constructor Thread(String
 name)
T
h
r
e
a
d
 
t
=
 
n
e
w
 
T
h
r
e
a
d
(
"
M
y
 
f
i
r
s
t
 
t
h
r
e
a
d
"
)
;
// the start() method moves the thread to the active state
t.start();
// getting the thread name by invoking the getName() method
String str = t.getName();
System.out.println(str);
}
}
 
U
s
i
n
g
 
t
h
e
 
T
h
r
e
a
d
 
C
l
a
s
s
:
T
h
r
e
a
d
(
R
u
n
n
a
b
l
e
 
r
,
 
S
t
r
i
n
g
 
n
a
m
e
)
 
public
 
class
 MyThread2 
implements
 Runnable  {
public
 
void
 run()
{
System.out.println(
"Now the thread is running ..."
);
}
public
 
static
 
void
 main(String argvs[])  {
// creating an object of the class MyThread2
Runnable r1 = 
new
 MyThread2();
// creating an object of the class Thread using Thread(Runnable r, String name)
Thread th1 = 
new
 Thread(r1, 
"My new thread"
);
// the start() method moves the thread to the active state
th1.start();
// getting the thread name by invoking the getName() method
String str = th1.getName();
System.out.println(str);
}  }
 
Example
 
class NameMyThread
{
public static void main (String []
args)
 {
    MyThread mt;
    if (args.length == 0)
         mt = new MyThread ();
    else mt = new MyThread (args
[0]);
     mt.start ();
     }
   }
class MyThread extends Thread {
    MyThread () {
   // The compiler creates the
byte code equivalent of super ();
   }
 MyThread (String name) {
    setName (name);
    // Pass name to Thread
superclass
   }
   public void run () {
    System.out.println ("My name
is: " + getName ());
   }
 }
 
S
l
e
e
p
 
(
l
o
n
g
 
m
i
l
l
i
s
e
c
o
n
d
s
)
 
It suspends a thread for the specified
period. If any other thread interrupts this
sleeping thread, it will throw an
InterruptedException. So it is suggested to
enclose the sleep() method in the try
block. Alternatively, the code’s method
must include InterruptedException in its
throws clause.
 
b
o
o
l
e
a
n
 
i
s
A
l
i
v
e
(
)
 
It determines if a thread is still running. JVM
considers a thread to be alive immediately
before calling to thread’s run() method, during
the execution of thread’s run() and immediately
after return from run().
During that interval, the isAlive() method returns
a “true” Boolean value. Otherwise, it returns
false.
This method is useful in the situations when
one thread needs to wait for another thread to
finish its run() method.
class MyThread extends Thread{
      public void run(){
     System.out.println("My
thread is in running
     state.");
}
 }
class ThreadSleepDemo{
     public static void main(String
args[]){
     MyThread obj=new MyThread();
     obj.start();
     while(obj.isAlive())
     {
      try {
           obj.sleep(10);
        } catch(InterruptedException
e) {
      System.out.println(“Sleeping
thread interrupted”);
      }
     System.out.println(“Thread-
Sleep Demo Complete”);
    }
   }
  }
 
j
o
i
n
(
l
o
n
g
 
m
i
l
l
i
s
e
c
o
n
d
s
)
 
T
h
i
s
 
m
e
t
h
o
d
 
g
e
t
s
 
c
a
l
l
e
d
 
w
h
e
n
 
a
 
t
h
r
e
a
d
 
w
a
n
t
s
 
t
o
w
a
i
t
 
f
o
r
 
a
n
o
t
h
e
r
 
t
h
r
e
a
d
 
t
o
 
t
e
r
m
i
n
a
t
e
.
 
L
e
t
s
 
s
e
e
 
a
s
a
m
p
l
e
 
c
o
d
e
 
f
o
r
 
t
h
e
 
<
j
o
i
n
(
)
>
 
m
e
t
h
o
d
.
class MyThread extends Thread{
     public void run(){
     System.out.println("My
thread is in running
     state.");
    }
 }
class ThreadJoinDemo{
     public static void main(String args[]){
     MyThread obj=new MyThread();
     obj.start();
     try {
        obj.join();
      }
      catch(InterruptedException e) {
      }
      System.out.println(“Thread-Join Demo
Complete”);
      }
     }
 }
 
 
Thread currentThread():
It returns the instance reference of the
currently executing thread.
T
h
r
e
a
d
.
S
t
a
t
e
 
g
e
t
S
t
a
t
e
(
)
:
It returns the state of the thread.
 
class ThreadStateTest {
   public static void main (String [] args) {
      Thread currentThread = Thread.currentThread();
      System.out.println(currentThread);
      MyThread mt1 = new MyThread ();
      mt1.setName("MyThread1");
      MyThread mt2 = new MyThread();
      mt1.setName("MyThread2");
      System.out.println("Thread State of MyThread1 before calling start:
"+mt1.getState());
      mt1.start ();
      mt2.start();
      System.out.println("Thread State of MyThread1 in Main method before
Sleep: " + mt1.getState());
      System.out.println("Thread State of MyThread2 in Main method before
Sleep: " + mt2.getState());
      try {
      Thread.sleep (1000);
      } catch (InterruptedException e) {
        }
      System.out.println("Thread State of MyThread1 in Main method after
Sleep: " + mt1.getState());
      System.out.println("Thread State of MyThread2 in Main method after
Sleep: " + mt2.getState());
     }
}
 
class MyThread extends Thread {
       public void run () {
     System.out.println ("Run by " +
Thread.currentThread().getName
 ());
    
 try {
         
 Thread.sleep (100);
       
} catch (InterruptedException e) {
         
 }
      
System.out.println("Thread State of: "+
Thread.currentThread().getName()+ " -
      
"+Thread.currentThread().getState());
      
System.out.println("Exit of Thread: " +
Thread.currentThread().getName());
     
}
   
 }
 
yield()
 
This method causes the currently executing
thread object to pause temporarily and allow
other threads to run.
public class ThreadTest extends Thread {
         public void run() {
             System.out.println("In run");
             yield();
             System.out.println("Leaving run");
         }
     public static void main(String []argv) {
     (new ThreadTest()).start();
     }
}
 
f
i
n
a
l
 
i
n
t
 
g
e
t
P
r
i
o
r
i
t
y
(
)
 
&
 
f
i
n
a
l
 
v
o
i
d
 
s
e
t
P
r
i
o
r
i
t
y
(
i
n
t
p
r
i
o
r
i
t
y
)
 
It returns the priority of the thread.
This function is used to change the priority of a
thread.
public class ThreadDemo {
public static void main(String[] args) {
       Thread t = Thread.currentThread();
       t.setName("Admin Thread"); // set thread priority to 1
       t.setPriority(1); // prints the current thread
       System.out.println("Thread = " + t); int priority= t.getPriority();
       System.out.println("Thread priority= " + priority);
       int count = Thread.activeCount();
       System.out.println("currently active threads = " + count);
     }
}
 
Cont..
 
i
n
t
 
g
e
t
I
d
(
)
:
It returns the id of the thread.
i
n
t
e
r
r
u
p
t
(
)
:
It interrupts the thread.
b
o
o
l
e
a
n
 
i
s
I
n
t
e
r
r
u
p
t
e
d
(
)
:
tests if the thread has been interrupted and returns
the interrupted flag either true or false.
b
o
o
l
e
a
n
 
i
n
t
e
r
r
u
p
t
e
d
(
)
:
The static interrupted() method tests if the thread
has been interrupted. This method returns the
interrupted flag after that it sets the flag to false if it
is true.
 
 
public class TestThreadInterrupt extends Thread {
    
 public void run() {
       
for (int i = 1; i <= 2; i++) {
          
if (Thread.interrupted()) {
                     System.out.println("code for interrupted
thread");
         
 } else {
                     
System.out.println("code for normal thread");
                
}
           
}
         
//end of for loop
        
 }
           
public static void main(String args[]) {
           TestThreadInterrupt t1 = new TestThreadInterrupt();
          
 TestThreadInterrupt t2 = new TestThreadInterrupt();
           t1.start();
           
t1.interrupt();
           
t2.start();
 }
}
 
Cont..
 
s
u
s
p
e
n
d
(
)
:
You can use it to suspend the
thread. 
[deprecated]
r
e
s
u
m
e
(
)
:
You can use it to resume the suspended
thread. 
[deprecated]
s
t
o
p
(
)
:
You can use it to halt the thread.
 
Thread Priority
 
Each thread has a priority. Priorities are represented
by a number between 1 and 10. In most cases, the
thread scheduler schedules the threads according to
their priority (known as preemptive scheduling). But it
is not guaranteed because it depends on JVM
specification that which scheduling it chooses. Note
that not only JVM a Java programmer can also assign
the priorities of a thread explicitly in a Java program.
 
65
 
Setter & Getter Method of Thread
Priority
 
p
u
b
l
i
c
 
f
i
n
a
l
 
i
n
t
 
g
e
t
P
r
i
o
r
i
t
y
(
)
:
 
T
h
e
j
a
v
a
.
l
a
n
g
.
T
h
r
e
a
d
.
g
e
t
P
r
i
o
r
i
t
y
(
)
 
m
e
t
h
o
d
 
r
e
t
u
r
n
s
 
t
h
e
p
r
i
o
r
i
t
y
 
o
f
 
t
h
e
 
g
i
v
e
n
 
t
h
r
e
a
d
.
p
u
b
l
i
c
 
f
i
n
a
l
 
v
o
i
d
 
s
e
t
P
r
i
o
r
i
t
y
(
i
n
t
n
e
w
P
r
i
o
r
i
t
y
)
:
 
T
h
e
 
j
a
v
a
.
l
a
n
g
.
T
h
r
e
a
d
.
s
e
t
P
r
i
o
r
i
t
y
(
)
m
e
t
h
o
d
 
u
p
d
a
t
e
s
 
o
r
 
a
s
s
i
g
n
 
t
h
e
 
p
r
i
o
r
i
t
y
 
o
f
 
t
h
e
t
h
r
e
a
d
 
t
o
 
n
e
w
P
r
i
o
r
i
t
y
.
 
T
h
e
 
m
e
t
h
o
d
 
t
h
r
o
w
s
I
l
l
e
g
a
l
A
r
g
u
m
e
n
t
E
x
c
e
p
t
i
o
n
 
i
f
 
t
h
e
 
v
a
l
u
e
n
e
w
P
r
i
o
r
i
t
y
 
g
o
e
s
 
o
u
t
 
o
f
 
t
h
e
 
r
a
n
g
e
,
 
w
h
i
c
h
 
i
s
 
1
(
m
i
n
i
m
u
m
)
 
t
o
 
1
0
 
(
m
a
x
i
m
u
m
)
.
 
66
 
C
o
n
s
t
a
n
t
s
 
D
e
f
i
n
e
d
 
i
n
 
T
h
r
e
a
d
C
l
a
s
s
 
1.
public static int MIN_PRIORITY
2.
public static int NORM_PRIORITY
3.
public static int MAX_PRIORITY
Default priority of a thread is 5
(NORM_PRIORITY). The value of MIN_PRIORITY
is 1 and the value of MAX_PRIORITY is 10.
 
67
 
Example
 
import
 java.lang.*;
public
 
class
 ThreadPriorityExample 
extends
 Thread  {
 
public
 
void
 run()  {
  System.out.println(
"Inside the run() method"
);
}
public
 
static
 
void
 main(String argvs[])
{
ThreadPriorityExample th1 = 
new
 ThreadPriorityExample();
ThreadPriorityExample th2 = 
new
 ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();
}
 
 
68
 
System.out.println(
"Priority of the thread th1 is : "
 + th
1.getPriority());
System.out.println(
"Priority of the thread th2 is : "
 + th
2.getPriority());
System.out.println(
"Priority of the thread th2 is : "
 + th
2.getPriority());
th1.setPriority(
6
);
th2.setPriority(
3
);
th3.setPriority(
9
);
System.out.println(
"Priority of the thread th1 is : "
 + th
1.getPriority());
System.out.println(
"Priority of the thread th2 is : "
+ th2.getPriority());
 
 
 
69
 
System.out.println(
"Priority of the thread th3 is : "
 +
 th3.getPriority());
System.out.println(
"Currently Executing The Thread
 : "
 + Thread.currentThread().getName());
System.out.println(
"Priority of the main thread is : "
 + Thread.currentThread().getPriority());
Thread.currentThread().setPriority(
10
);
System.out.println(
"Priority of the main thread is : "
 + Thread.currentThread().getPriority());
        
}
}
 
70
 
S
y
n
c
h
r
o
n
i
z
a
t
i
o
n
 
Synchronization in Java is the capability to
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.
 
71
 
W
h
y
 
u
s
e
 
S
y
n
c
h
r
o
n
i
z
a
t
i
o
n
?
 
The synchronization is mainly used to
1.
To prevent thread interference.
2.
To prevent consistency problem.
 
72
 
T
y
p
e
s
 
o
f
 
S
y
n
c
h
r
o
n
i
z
a
t
i
o
n
 
There are two types of synchronization
.
Process Synchronization
Thread Synchronization
 
 
73
 
T
h
r
e
a
d
 
S
y
n
c
h
r
o
n
i
z
a
t
i
o
n
 
There are two types of thread synchronization
mutual exclusive and inter-thread
communication.
1.
Mutual Exclusive
1.
Synchronized method.
2.
Synchronized block.
3.
Static synchronization.
2.
Cooperation (Inter-thread communication in
java)
 
74
 
M
u
t
u
a
l
 
E
x
c
l
u
s
i
v
e
 
Mutual Exclusive helps keep threads from
interfering with one another while sharing
data. It can be achieved by using the
following three ways:
1.
By Using Synchronized Method
2.
By Using Synchronized Block
3.
By Using Static Synchronization
 
75
 
C
o
n
c
e
p
t
 
o
f
 
L
o
c
k
 
i
n
 
J
a
v
a
 
Synchronization is built around an internal
entity known as the lock or monitor. Every
object has a lock associated with it. By
convention, a thread that needs consistent
access to an object's fields has to acquire
the object's lock before accessing them,
and then release the lock when it's done
with them.
 
76
 
E
x
a
m
p
l
e
 
W
i
t
h
o
u
t
 
S
y
n
c
h
r
o
n
i
z
a
t
i
o
n
 
c
l
a
s
s
 
T
a
b
l
e
{
v
o
i
d
 
p
r
i
n
t
T
a
b
l
e
(
i
n
t
 
n
)
{
//method not synchronized
f
o
r
(
i
n
t
 
i
=
1
;
i
<
=
5
;
i
+
+
)
{
     System.out.println(n*i);
t
r
y
{
      Thread.sleep(
400
);
}
c
a
t
c
h
(
E
x
c
e
p
t
i
o
n
 
e
)
{
S
y
s
t
e
m
.
o
u
t
.
p
r
i
n
t
l
n
(
e
)
;
}
   }
 }
 }
 
77
 
class
 MyThread1 
extends
 Thread{
        Table t;
        MyThread1(Table t){
                   this
.t=t;
           }
       public
 
void
 run(){
        t.printTable(
5
);
       }
 }
 
78
 
class
 MyThread2 
extends
 Thread{
        Table t;
        MyThread2(Table t){
        this
.t=t;
       }
      public
 
void
 run(){
     t.printTable(
100
);
     }
 }
 
79
 
class
 TestSynchronization1{
        public
 
static
 
void
 main(String args[]){
        Table obj = 
new
 Table();
//only one object
        MyThread1 t1=
new
 MyThread1(obj);
        MyThread2 t2=
new
 MyThread2(obj);
        t1.start();
        t2.start();
       }
   }
 
80
 
Output : 5
             100
             10
              200
              15
              300
              20
              400
              15
              500
 
81
 
S
y
n
c
h
r
o
n
i
z
e
d
 
M
e
t
h
o
d
 
If you declare any method as
synchronized, it is known as synchronized
method.
Synchronized method is used to lock an
object for any shared resource.
When a thread invokes a synchronized
method, it automatically acquires the lock
for that object and releases it when the
thread completes its task.
 
82
 
Example With Synchronization
 
c
l
a
s
s
 
T
a
b
l
e
{
S
y
n
c
h
r
o
n
i
z
e
d
 
v
o
i
d
 
p
r
i
n
t
T
a
b
l
e
(
i
n
t
 
n
)
{
//method not synchronized
f
o
r
(
i
n
t
 
i
=
1
;
i
<
=
5
;
i
+
+
)
{
     System.out.println(n*i);
t
r
y
{
      Thread.sleep(
400
);
}
c
a
t
c
h
(
E
x
c
e
p
t
i
o
n
 
e
)
{
S
y
s
t
e
m
.
o
u
t
.
p
r
i
n
t
l
n
(
e
)
;
}
   }
 }
 }
 
83
 
class
 MyThread1 
extends
 Thread{
        Table t;
        MyThread1(Table t){
                   this
.t=t;
           }
       public
 
void
 run(){
        t.printTable(
5
);
       }
 }
 
84
 
class
 MyThread2 
extends
 Thread{
        Table t;
        MyThread2(Table t){
        this
.t=t;
       }
      public
 
void
 run(){
     t.printTable(
100
);
     }
 }
 
85
 
class
 TestSynchronization1{
        public
 
static
 
void
 main(String args[]){
        Table obj = 
new
 Table();
//only one object
        MyThread1 t1=
new
 MyThread1(obj);
        MyThread2 t2=
new
 MyThread2(obj);
        t1.start();
        t2.start();
       }
   }
 
86
 
Output : 5
             10
             15
              20
              25
              100
              200
              300
              400
              500
 
87
 
S
y
n
c
h
r
o
n
i
z
e
d
 
m
e
t
h
o
d
 
b
y
 
u
s
i
n
g
a
n
n
o
n
y
m
o
u
s
 
c
l
a
s
s
 
c
l
a
s
s
 
T
a
b
l
e
{
S
y
n
c
h
r
o
n
i
z
e
d
 
v
o
i
d
 
p
r
i
n
t
T
a
b
l
e
(
i
n
t
 
n
)
{
//method not synchronized
f
o
r
(
i
n
t
 
i
=
1
;
i
<
=
5
;
i
+
+
)
{
     System.out.println(n*i);
t
r
y
{
      Thread.sleep(
400
);
}
c
a
t
c
h
(
E
x
c
e
p
t
i
o
n
 
e
)
{
S
y
s
t
e
m
.
o
u
t
.
p
r
i
n
t
l
n
(
e
)
;
}
   }
 }
 }
 
88
 
p
u
b
l
i
c
 
c
l
a
s
s
 
T
e
s
t
S
y
n
c
h
r
o
n
i
z
a
t
i
o
n
3
{
 
 
 
 
 
 
 
p
u
b
l
i
c
 
s
t
a
t
i
c
 
v
o
i
d
 
m
a
i
n
(
S
t
r
i
n
g
 
a
r
g
s
[
]
)
{
 
 
 
 
 
 
 
f
i
n
a
l
 
T
a
b
l
e
 
o
b
j
 
=
 
n
e
w
 
T
a
b
l
e
(
)
;
       //only one object
 
 
 
 
 
 
T
h
r
e
a
d
 
t
1
=
n
e
w
 
T
h
r
e
a
d
(
)
{
 
 
 
 
 
 
 
p
u
b
l
i
c
 
v
o
i
d
 
r
u
n
(
)
{
       obj.printTable(
5
);
      }
   };
 
89
 
Thread t2=
new
 Thread(){
        public
 
void
 run(){
       obj.printTable(
100
);
      }
};
 
t1.start();
 t2.start();
      }
}
 
90
 
S
t
a
t
i
c
 
S
y
n
c
h
r
o
n
i
z
a
t
i
o
n
 
If you make any static method as synchronized,
the lock will be on the class not on object.
 
91
 
P
r
o
b
l
e
m
 
w
i
t
h
o
u
t
 
s
t
a
t
i
c
 
s
y
n
c
h
r
o
n
i
z
a
t
i
o
n
 
Suppose there are two objects of a shared class
(e.g. Table) named object1 and object2. In case of
synchronized method and synchronized block there
cannot be interference between t1 and t2 or t3 and
t4 because t1 and t2 both refers to a common
object that have a single lock. But there can be
interference between t1 and t3 or t2 and t4
because t1 acquires another lock and t3 acquires
another lock. We don't want interference between
t1 and t3 or t2 and t4. Static synchronization solves
this problem.
 
92
 
Example
 
class
 Table  {
 
synchronized
 
static
 
void
 printTable(
int
 n){
   
for
(
int
 i=
1
;i<=
10
;i++){
     System.out.println(n*i);
     
try
{
       Thread.sleep(
400
);
     }  
catch
(Exception e){}
   }
 }  }
 
93
 
class
 MyThread1 
extends
 Thread{
      public
 
void
 run(){
      Table.printTable(
1
);
      }
   }
class
 MyThread2 
extends
 Thread{
      public
 
void
 run(){
      Table.printTable(
10
);
    }
}
 
94
 
class
 MyThread1 
extends
 Thread{
      public
 
void
 run(){
      Table.printTable(
100
);
      }
   }
class
 MyThread2 
extends
 Thread{
      public
 
void
 run(){
      Table.printTable(
1000
);
    }
}
 
95
 
public
 
class
 TestSynchronization4{
          public
 
static
 
void
 main(String t[]){
          MyThread1 t1=
new
 MyThread1();
          MyThread2 t2=
new
 MyThread2();
          MyThread3 t3=
new
 MyThread3();
          MyThread4 t4=
new
 MyThread4();
          t1.start();
          t2.start();
          t3.start();
          t4.start();
         }
}
 
96
Slide Note
Embed
Share

Explore the concepts of multithreading and multiprocessing at Amity School of Engineering & Technology. Learn about the types of multiprocessing, threads, thread life cycle, advantages of multithreading, and the importance of user and daemon threads in Java programming. Dive into the world of utilizing the CPU efficiently through parallel processing techniques.

  • Multithreading
  • Multiprocessing
  • Amity School
  • Engineering & Technology
  • Java Programming

Uploaded on Jul 22, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. Amity School of Engineering & Technology Multithreading 1

  2. Amity School of Engineering & Technology Agenda Multiprocessing Type of Multiprocessing What is Thread Type of Thread Multithreading Thread Life Cycle Multithreading Example Advantages of Multithreading

  3. Amity School of Engineering & Technology What is Multiprocessing The process of using the entire CPU of the computer and being capable to execute more then two processes or computational jobs at a time is defined as multiprocessing.

  4. Amity School of Engineering & Technology Type of Multiprocessing There are two type of Multiprocessing in java. 1) Process-Based Multiprocessing 2) Thread Based Multiprocessing Multiprocessing Process Based Thread Based

  5. Amity School of Engineering & Technology

  6. Amity School of Engineering & Technology What is Thread(Separate flow of Execution) A thread is an individual, light weight, and a smallest unit of a given process. There are multiple thread in a single process and each thread is independent of the other. As shown in figure ,a thread is executed inside the process .There is a context switching between the threads. There can be multiple processes inside the OS and one process can have multiple threads.

  7. Amity School of Engineering & Technology

  8. Amity School of Engineering & Technology

  9. Amity School of Engineering & Technology Type of Thread 1. User Thread 2. Daemon Thread User threads are high-priority threads. The JVM will wait for any user thread to complete its task before terminating it. On the other hand, daemon threads are low- priority threads whose only role is to provide services to user threads

  10. Amity School of Engineering & Technology Use of Daemon Thread Daemon threads are useful for background supporting tasks such as garbage collection, releasing memory of unused objects and removing unwanted entries from the cache. Most of the JVM threads are daemon threads.

  11. Amity School of Engineering & Technology

  12. Amity School of Engineering & Technology Multithreading Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process. Threads can be created by using two mechanisms : 1.Extending the Thread class 2.Implementing the Runnable Interface

  13. Amity School of Engineering & Technology Cont..

  14. Amity School of Engineering & Technology Advantages of multithread The users are not blocked because threads are independent, and we can perform multiple operations at times As such the threads are independent, the other threads won t get affected if one thread meets an exception.

  15. Amity School of Engineering & Technology Thread Life Cycle in Java

  16. Amity School of Engineering & Technology New state Before calling the start() method on the newly created thread instance, the thread is in a new state . In this phase, the thread is created using class Thread class . It remains in this state till the program starts the thread. It is also known as born thread.

  17. Amity School of Engineering & Technology Runnable state The thread is in a runnable state after calling the start() method, but it has not been selected as the running thread by the thread scheduler. In this phase, the instance of the thread is invoked with a start method. The thread control is given to scheduler to finish the execution. It depends on the scheduler, whether to run the thread.

  18. Amity School of Engineering & Technology Running state If the thread scheduler has selected it as a running thread, it is on the running state . A thread will only execute its task when it is on the running state .

  19. Amity School of Engineering & Technology Waiting state When a thread is still alive but not eligible to run, then the thread is in the waitingstate . A thread can move from runningstate to waitingstate by certain conditions ex: sleep(), wait(). Same as that a thread can move from waitingstate to runnablestate by certain conditions ex: notify(), interrupt().

  20. Amity School of Engineering & Technology Death state or Terminate When a thread completes all of the tasks assigned to it, or when its run() method exits, it will become a dead thread.

  21. Amity School of Engineering & Technology Example package demotest; public class GuruThread { public static void main(String[] args) { System.out.println("Single Thread"); } }

  22. Amity School of Engineering & Technology Creating Threads We can create threads in two different ways, They are 1.Extend Thread class 2.Implement Runnable interface The behaviour of the thread object will be the same in both ways.

  23. Amity School of Engineering & Technology Method 1-Extend thread class public class Mythread extends Thread{ @Override public void run(){ System.out.println("Hi!! This is from child thread"); } }public class Application { public static void main(String[] args) { Mythread mythread=new Mythread(); mythread.start(); }}

  24. Amity School of Engineering & Technology What is start() method and run() method? We override the run() method and specify the tasks we want to assign to the newly created thread. Then we call the start() method on the thread instance that we created. Please keep in mind that the start() method is belongs to Thread class, and it will call the run() method internally.

  25. Amity School of Engineering & Technology What happens if we didn t override the run() Method? A thread will be created, but it does nothing and then it will go to death state. public class Mythread extends Thread{ //we didn't override run() method here } public class Application { public static void main(String[] args) { Mythread mythread=new Mythread(); mythread.start(); }

  26. Amity School of Engineering & Technology Explanation When we invoke the start() method, A thread will be created. start() method will invoke the run() method internally. Then JVM checks whether the child class contains a run() method. If yes then child class s run method will be executed. If not JVM will execute the parent (Thread) class s run() method. In Java Thread class s run() method doesn t contain any tasks in its body. Therefore if we didn t override the run() method, the Thread class s run() method will be invoked and it does nothing.

  27. Amity School of Engineering & Technology Can we overload the run() method? @Override public void run(){ System.out.println("Hi!! This is from child thread default run method"); } public void run(String name){ System.out.println("Hi!! This is from child thread's over loaded method"); } public class Mythread extends Thread{ } public class Application { public static void main(String[] args) { Mythread mythread=new Mythread(); mythread.start(); }}

  28. Amity School of Engineering & Technology Explanation Yes we can overload the run() method. but start() method will only invoke run() method which has no arguments. Therefore the overloaded run() method will not be invoked by start() method.

  29. Amity School of Engineering & Technology Can we invoke run() method instead of start() method? public class Mythread extends Thread{ @Override public void run(){ System.out.println( This method is executed by: +Thread.currentThread.getName()); } } public class Application { public static void main(String[] args) { Mythread mythread=new Mythread(); //mythread.start(); Mythread.run(); } }

  30. Amity School of Engineering & Technology Explanation We can invoke the run() method directly. but it will not create a new child thread. Instead, parent thread will execute the child thread object s run() method. This will be a typical OOP method invoking.

  31. Amity School of Engineering & Technology Can we override the start() method? @Override public void run(){ System.out.println( This is run method ); } @Override public void start(){ System.out.println( This is start method ); } public class Mythread extends Thread{ } public class Application { public static void main(String[] args) { Mythread mythread=new Mythread(); mythread.start(); } }

  32. Amity School of Engineering & Technology Drawbacks of this way of Thread Creation We know Java doesn t support multiple inheritances. In this way, Since user-created class (Mythread) Inherits the characteristics from Thread class , user-created class (Mythread)can t inherit another class.

  33. Amity School of Engineering & Technology Method 2: Implement the Runnable Interface To create a thread by runnable interface we must create a class that implements runnable interface. public class Rnblthread implements Runnable{ @Override public void run() { System.out.println("Hi!! This is from a child thread which is created by runnable interface"); } }

  34. Amity School of Engineering & Technology Cont.. After implementing the runnable interface we can simply create the thread by creating a thread object. public class Application { public static void main(String[] args) { Runnable r=new Rnblthread(); Thread mythread= new Thread(r); mythread.start(); } }

  35. Amity School of Engineering & Technology

  36. Amity School of Engineering & Technology Cont.. 1.NEW a newly created thread that has not yet started the execution 2.RUNNABLE either running or ready for execution but it's waiting for resource allocation 3.BLOCKED waiting to acquire a monitor lock to enter or re-enter a synchronized block/method 4.WAITING waiting for some other thread to perform a particular action without any time limit 5.TIMED_WAITING waiting for some other thread to perform a specific action for a specified

  37. Amity School of Engineering & Technology New Runnable runnable = newNewState(); Thread t = newThread(runnable); Log.info(t.getState());

  38. Amity School of Engineering & Technology Runnable When we've created a new thread and called the start() method on that, it's moved from NEW to RUNNABLE state. Threads in this state are either running or ready to run, but they're waiting for resource allocation from the system In a multi-threaded environment, the Thread- Scheduler (which is part of JVM) allocates a fixed amount of time to each thread. So it runs for a particular amount of time, then relinquishes the control to other RUNNABLE threads.

  39. Amity School of Engineering & Technology Example Runnable runnable = newNewState(); Thread t = newThread(runnable); t.start(); Log.info(t.getState());

  40. Amity School of Engineering & Technology Blocked A thread is in the BLOCKED state when it's currently not eligible to run. It enters this state when it is waiting for a monitor lock and is trying to access a section of code that is locked by some other thread.

  41. Amity School of Engineering & Technology Example import java.util.logging.LogManager; Impoort java.util.logging.Logger; publicclassBlockedState { publicstaticvoidmain(String[] args) throws InterruptedException { Thread t1 = newThread(newDemoThreadB()); Thread t2 = newThread(newDemoThreadB()); LogManager lgmngr=LogManager.getLogManager(); Logger log=lgmngr.getLogger(Logger.GLOBAL_LOGGER_NAME); t1.start(); t2.start(); Thread.sleep(1000); log.info(String.valueOf(t2.getState())); System.exit(0); } }

  42. Amity School of Engineering & Technology Example classDemoThreadBimplementsRunnable { @Override publicvoidrun() { commonResource(); } publicstaticsynchronizedvoid commonResource() { while(true) { // Infinite loop to mimic heavy processing // 't1' won't leave this method // when 't2' try to enter this } } }

  43. Amity School of Engineering & Technology Explanation 1.We've created two different threads t1 and t2 2.t1 starts and enters the synchronized commonResource() method; this means that only one thread can access it; all other subsequent threads that try to access this method will be blocked from the further execution until the current one will finish the processing 3.When t1 enters this method, it is kept in an infinite while loop; this is just to imitate heavy processing so that all other threads cannot enter this method 4.Now when we start t2, it tries to enter the commonResource() method, which is already being accessed by t1, thus, t2 will be kept in the BLOCKED state

  44. Amity School of Engineering & Technology List of Commonly Used Thread class Constructors. Thread class has the following eight constructors. Thread(): It creates a Thread object with a default name. Thread(String name): It creates a Thread object with a name that the name argument specifies. Thread (Runnable r): This method constructs Thread with a parameter of the Runnable object that defines the run() method. Thread (Runnable r, String name): This method creates Thread with a name and a Runnable object parameter to set the run() method. Thread(ThreadGroup group, Runnable target): It creates a Thread object with a Runnable object and the group to which it belongs.

  45. Amity School of Engineering & Technology Thread (ThreadGroup group, Runnable target, String name): It creates Thread object with a Runnable object that defines the run() method, specified name as its name and the Thread object belongs to the ThreadGroup referred to by the group. Thread(ThreadGroup group, String name): It creates a thread that has the specified name and associates to the ThreadGroup given as the first parameter. Thread(ThreadGroup group, Runnable target, String name, long stackSize): this constructor specifies the ThreadGroup parameter, the size of the thread s method-call stack.

  46. Amity School of Engineering & Technology Commonly used methods of Thread class 1. public void run(): is used to perform action for a thread. 2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread. 3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. 4. public void join(): waits for a thread to die. 5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds. 6. public int getPriority(): returns the priority of the thread. 7. public int setPriority(int priority): changes the priority of the thread. 8. public String getName(): returns the name of the thread.

  47. Amity School of Engineering & Technology 9. public void setName(String name): changes the name of the thread. 10. public Thread currentThread(): returns the reference of currently executing thread. 11. public int getId(): returns the id of the thread. 12. public Thread.State getState(): returns the state of the thread. 13. public boolean isAlive(): tests if the thread is alive. 14. public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute. 15. public void suspend(): thread(depricated). 16. public void resume(): is used to resume the suspended thread(depricated). 17. public void stop(): is used to stop the thread(depricated) is used to suspend the

  48. Amity School of Engineering & Technology 18. public boolean isDaemon(): tests if the thread is a daemon thread. 19. public void setDaemon(boolean b): marks the thread as daemon or user thread. 20. public void interrupt(): interrupts the thread. 21. public boolean isInterrupted(): tests if the thread has been interrupted. 22. public static boolean interrupted(): tests if the current thread has been interrupted.

  49. Amity School of Engineering & Technology Thread Example by implementing Runnable interface class Multi3 implements Runnable{ public void run(){ System.out.println("thread is running..."); } public static void main(String args[]){ Multi3 m1=new Multi3(); Thread t1 =new Thread(m1); // Using the constructor Thread(R unnable r) t1.start(); } }

  50. Amity School of Engineering & Technology Example getName() public class MyThread1 { // Main method public static void main(String argvs[]) { // creating an object of the Thread class using the constructor Thread(String name) Thread t= new Thread("My first thread"); // the start() method moves the thread to the active state t.start(); // getting the thread name by invoking the getName() method String str = t.getName(); System.out.println(str); } }

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#