Life cycle of Thread tells the various information of thread
form born to terminate. Thread life cycle contains the several stages and at a
time any thread can be present in a
single state.
States of Thread life cycle
Born
Ready
Running
Blocked
Sleep
Wait
Dead
Java Thread Life Cycle
Ready: In this state thread is ready to execute but not running.
When the start() method calls thread enters from born to ready state.
Running: When a run() method executes highest priority ready thread assigned a processor and enter in a running state for execution.
Thread can visit more than ones in a running state.
Blocked:
When a running thread has a input-output issue it enters in a blocked state
from running state and when input-output issue solves it again comes in a
running thread.
Sleep : A running thread enter in a sleep state for a specified number of milliseconds when a sleep() method calls.
When sleep time expires then thread moves to ready state.
Wait : When a low priority thread executing and high priority thread comes then high priority thread get preference and enter in a running state. Then low priority thread leaves a running state and moves to wait state for indefinite time.
When a high priority thread execution completes it calls waiting thread for execution by notify () & notifyall () method.
Dead:
A running thread is enter in a dead state when its execution completes (run()
method completes) or terminate for any reason.
In computing, producer–consumer problem also known as the bounded-buffer problem.
In the producer–consumer problem there are two processes, first is producerand the second is consumer, who share a common, fixed-size buffer.
The producer’s job is to generate data, put it
into the buffer and start again.
At the same
time, the consumer’s job is consuming the data, one piece at a time and removing
it from the buffer.
The producer–consumer
problem occurs when the producer try to add data into the buffer if it’s
full and the same consumer try to remove data from an empty buffer.
Solution of Producer & Consumer
The solution for the producer must go to sleep if the buffer is full and the consumer must consume data.
Once the data is consumed it removes from the buffer by consumer process. Consumer process also notifies the producer, to starts fill the buffer again.
Similarly, the consumer process must go to sleep if it finds the buffer is empty and the producer puts data into the buffer.
Ones the data is filled into buffer by producer process it also notifies the Consumer, to starts consume the data from buffer.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
classItem{
intn;
booleancondition=false;
synchronized intget(){
while(!condition)
try{
wait();
}catch(InterruptedExceptione){
System.out.println("Exception caught");
}
System.out.println("Got: "+n);
condition=false;
notify();
returnn;
}
synchronized voidput(intx){
while(condition)
try{
wait();
}catch(InterruptedExceptione){
System.out.println("Exception caught");
}
n=x;
condition=true;
System.out.println("Put: "+n);
notify();
}
}
classProducerimplementsRunnable{
Itemq;
Producer(Item q1){
q=q1;
newThread(this,"Producer").start();
}
publicvoidrun(){
inti=0;
while(true){
q.put(i++);
}
}
}
classConsumerimplementsRunnable{
Itemq;
Consumer(Item q1){
q=q1;
newThread(this,"Consumer").start();
}
publicvoidrun(){
while(true){
q.get();
}
}
}
publicclassPCDemo{
publicstaticvoidmain(Stringargs[]){
Itemq=newItem();
newProducer(q);
newConsumer(q);
System.out.println("Press Control-C to stop.");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Press Control-Ctostop.
Put:0
Got:0
Put:1
Got:1
Put:2
Got:2
Put:3
Got:3
Put:4
Got:4
Put:5
Got:5
Put:6
Got:6
Put:7
Got:7
Put:8
Got:8
Description : In the above program there are four classes: Item, Producer, Consumer and PCDemo
Item: the class is trying to synchronize.
Producer: produces the data.
Consumer: consumes the data produced by producer class.
PCDemo: a class that creats the class Item, Producer and Consumer.
In the above program we can see that, producer process producess
the data and consumed by consuner
process, then again a producer process producess a new data and consumed by consumer
process and so on.
When two or more threads try to access the same resource, they need somehow to ensure that the resource will be used by only one thread at a time.
The process by which this achive is called Synchronization. Java uses the concept of monitor (also called semaphore) for Synchronization.
The monitor allows one thread at a time to execute a Synchronized method. Only
one thread at a time may hold a lock on a monitor.
For a thread can lock or unlock each object in Java is associated with a
monitor.
Example: Write a program to synchronize a thread.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
classDemo{
voidwrite(Stringmsg){
System.out.print("["+msg);
try{
Thread.sleep(1000);
}catch(InterruptedExceptione){
System.out.println("Interrupted");
}
System.out.println("]");
}
}
classCallerimplementsRunnable{
Stringmsg;
Demo obj;
Threadt;
publicCaller(Demo obj1,Strings){// constructor
obj=obj1;
msg=s;
t=newThread(this);
t.start();
}
publicvoidrun(){
obj.write(msg);
}
}
publicclassSynchronizedMain{
publicstaticvoidmain(Stringargs[]){
Demo obj=newDemo();
Caller ob1=newCaller(obj,"Hello");
Caller ob2=newCaller(obj,"Hi");
Caller ob3=newCaller(obj,"Students");
// wait for threads to end
try{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}catch(InterruptedExceptione){
System.out.println("Interrupted");
}
}
}
1
2
3
[Hi[Hello[Students]
]
]
In the above program, nothing exist to stop all three threads from entering write () method while other thread is using it.
These three threads are racing each other to complete the method and this condition is known as a race condition.
To fix this program, we must serialize access to write () method and restrict its access to only one thread at a time.
To do this, we simply need to write synchronized keyword before write () method definition. It is known as a synchronized method.
Synchronized Method
1
2
3
4
// synchronize calls to call()
synchronized voidwrite(Stringmsg){
.....
}
above method write() can be changed as below
1
2
3
4
5
6
7
8
9
10
synchronized voidwrite(Stringmsg){
System.out.print("["+msg);
try{
Thread.sleep(1000);
}catch(InterruptedExceptione){
System.out.println("Interrupted");
}
System.out.println("]");
}
}
Synchronized block: this technique is also used for thread synchronization
1
2
3
4
5
6
//synchronize calls to call()
voidwrite(Stringmsg){
synchronized(msg){
...............
}
}
using synchronization block we can change write method as below
1
2
3
4
5
6
7
8
9
10
synchronized voidwrite(Stringmsg){
System.out.print("["+msg);
try{
Thread.sleep(1000);
}catch(InterruptedExceptione){
System.out.println("Interrupted");
}
System.out.println("]");
}
}
This prevent other threads from entering in write () method while other thread is using it. After synchronized has been added to write (), the output of the program.
In java, when two or more than two thread is computing for CPU time, every
thread is assigned a priority value. A highest Priority thread get preference
over lower priority thread.
All Java threads have a priority in the range
1-10.
Top priority is 10, lowest priority is
1.Normal priority ie. priority by default is 5.
Thread.MIN_PRIORITY – 1 minimum thread priority
Thread.MAX_PRIORITY – 10 maximum thread priority
Thread.NORM_PRIORITY – 5 maximum thread priority
Whenever a new Java thread is created it has
the same priority as the thread which created it.
Thread priority can be changed by the setPriority()
method.
Example: Write a program to demonstrate the thread priority.
A thread is light weight process that can execute simultaneously. Multithreading in java allows multiple threads to run simultaneously.
A program can be divided into two or more parts that can run concurrently and each part of such program is known as thread.
In a simple word, thread is a lightweight sub-process.
It is a smallest unit of processing.
When these threads execute concurrently for accomplishing a task is known multithreading.
In multithreading, each thread defines a separate path of execution.
In multithreading, every thread has a priority between 1 to 10. Thread with highest priority get preference over lower priority thread for execution.
Java Process and Thread Diagram
In a java programming, Thread is a predefined class within a java.lang package.
Operating system (OS) can contain multiple process, in the above figure, there are three process P1,P2 & P3, within OS and within P3 process there are three threads T1, T2& T3. There is context-switching between the threads.
2 Difference between Process and Thread
Process
Thread
A process has their own virtual address space.
Threads are entities within a process it uses its virtual address space of process.
Two processes running on the same system at the same time do not uses address space.
Two threads running within a process uses the same address space.
Every process has its own data segment
All threads within the process uses the same data segment of process.
In multiprocessing, processes use inter process communication techniques to interact with other processes.
In multithreading, threads do not uses inter process communication techniques because they not uses separate address spaces. They share the same address space therefore, they can communicate directly with other threads within process.
Processes have considerable overhead.
Threads have almost no overhead;
Process is heavy weight.
Threads are light weight process (LWP).
Process contains much information about system, resource.
Threads carry less state information than process
When we create a child process from a parent process then it requires duplication of the resources of parent process.
No duplication of resources is required when we create a child thread from main thread.
3 How to create a thread in Java
We can
create a thread by two ways:
By extending Thread
By implementing Runnable interface
Lets see multithreading in java with example
A Creating Thread By Implementing Runnable Interface
We can create a thread by creating a class that implements the Runnable interface.
To implement Runnable, a class only need to implement a single method called run().
Inside run () we will define the code that constitute the new thread.
When a new thread creates, it do not executes until we call its start () method. When start () method executes it call to run() method.
Below is the multithreading program in java with implementing runnable interface
Example: Print hello to illustrate multithreading example in java
1
2
3
4
5
6
7
8
9
10
publicclassThreadTest1implementsRunnable{
publicvoidrun(){
System.out.println("Hello from run");
}
publicstaticvoidmain(String[]s){
ThreadTest tt=newThreadTest();
Threadt=newThread(tt);
t.start();
}
}
Output
1
Hello from run
Creating more than one thread in java :- multithreading in java example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
publicclassThreadTest3implementsRunnable{
publicvoidrun(){
try{
for(inti=0;i<10;i++){
System.out.println("Hello from run "+i);
Thread.sleep(5000);
}
}
catch(InterruptedExceptione){
System.out.println("InterruptedException "+e);
}
}
publicstaticvoidmain(String[]s){
ThreadTest3 tt=newThreadTest3();
Threadt=newThread(tt);
t.start();
Thread t1=newThread(tt);
t1.start();
}
}
Output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Hello from run0
Hello from run0
Hello from run1
Hello from run1
Hello from run2
Hello from run2
Hello from run3
Hello from run3
Hello from run4
Hello from run4
Hello from run5
Hello from run5
Hello from run6
Hello from run6
Hello from run7
Hello from run7
Hello from run8
Hello from run8
Hello from run9
Hello from run9
Another Example of Thread is
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
classDemoimplementsRunnable{
Threadt;
Demo(){// creating a new, second thread
t=newThread(this,"DemoThread");
System.out.println("Child Thread= "+t);
t.start();// start a thread & call run()
}
publicvoidrun(){
try{
for(inti=5;i>0;i--){
System.out.println("Child Thread: "+i);
Thread.sleep(500);// Let the thread sleep for a while.
}
}catch(InterruptedExceptione){
System.out.println("Child exception ");
}
System.out.println("exit child thread");
}
}
publicclassCreateThread{
publicstaticvoidmain(Stringargs[]){
newDemo();
try{
for(inti=5;i>0;i--){
System.out.println(" Main Thread: "+i);
Thread.sleep(1000);// Let the thread sleep for a while.
}
}catch(InterruptedExceptione){
System.out.println("main exception ");
}
System.out.println("exit main thread");
}
}
Result
1
2
3
4
5
6
7
8
9
10
11
12
13
ChildThread=Thread[DemoThread,5,main]
ChildThread:5
Main Thread:5
ChildThread:4
Main Thread:4
ChildThread:3
ChildThread:2
Main Thread:3
ChildThread:1
exit childthread
Main Thread:2
Main Thread:1
exit main thread
Description:
Passing “this” as a argument, “DemoThread” is the name of the thread.
In this program, main thread fineshes last because the main thread sleeps for 1000 milliseconds (1 seconds) between iteration, but the child thread sleeps for only 500 milliseconds.
This cause the child thread terminates earlier than main thread.
B Creating Thread By Extending Thread Class
To create a thread we will create a thread a class that extends Thread class.
To extend Thread class, a class only needs to implement a single method called run (). This extending class must override the run() method
Inside run () we will define the code that constitute the new thread.
When a new thread creates, it do not executes until we call its start () method. When start () method executes it call to run() method.
Example: Write a thread program in java by extending thread class.
1
2
3
4
5
6
7
8
9
publicclassThreadTestextendsThread{
publicvoidrun(){
System.out.println("Hello from run");
}
publicstaticvoidmain(String[]s){
ThreadTestt=newThreadTest();
t.start();
}
}
1
Hello from run
Example: Write a program to show multithreading in java by extending thread class
1
2
3
4
5
6
7
8
9
publicclassThreadTestextendsThread{
publicvoidrun(){
System.out.println("Hello from run");
}
publicstaticvoidmain(String[]s){
ThreadTestt=newThreadTest();
t.start();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Hello from run0
Hello from run0
Hello from run1
Hello from run1
Hello from run2
Hello from run2
Hello from run3
Hello from run3
Hello from run4
Hello from run4
Hello from run5
Hello from run5
Hello from run6
Hello from run6
Hello from run7
Hello from run7
Hello from run8
Hello from run8
Hello from run9
Hello from run9
Multithreading in java example using Thread class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
classDemoextendsThread{
Demo(){
super("DemoThread");// creating a new, second thread
System.out.println("Child Thread= "+this);
start();// start a thread
}
publicvoidrun()// entry point for new Thread
{
try{
for(inti=5;i>0;i--){
System.out.println("Child Thread: "+i);
Thread.sleep(500);// thread sleep for a while.
}
}catch(InterruptedExceptione){
System.out.println("Child exception ");
}
System.out.println("exit child thread");
}
}
publicclassTest{
publicstaticvoidmain(Stringargs[]){
newDemo();// call constructor
try{
for(inti=5;i>0;i--){
System.out.println(" Main Thread: "+i);
Thread.sleep(1000);// thread sleep for a while.
}
}catch(InterruptedExceptione){
System.out.println("main exception ");
}
System.out.println("exit main thread");
}
}
Result
1
2
3
4
5
6
7
8
9
10
11
12
13
ChildThread=Thread[DemoThread,5,main]
Main Thread:5
ChildThread:5
ChildThread:4
Main Thread:4
ChildThread:3
ChildThread:2
Main Thread:3
ChildThread:1
exit childthread
Main Thread:2
Main Thread:1
exit main thread
4 Thread Methods in Java
Commonly used methods of Thread class are as follows
Sr No
Method and Description
1
void run() Work execute as a thread is defined in this method .
2
void start() Used to start a thred which Calls the run() method of the thread or child class.
3
static void sleep(long miliseconds) Suspend the thread for specified amount of time.
4
static void sleep(long miliseconds,int nanos) Suspend the thread for specified amount of time.
5
void join() This method is used to pause the ececution of current thread until it die.
void join().
6
void join(long miliseconds) Pause the execution of current thread for the pecified miliseconds.
7
void join(long miliseconds,int nanos) Pause the execution of current thread for the pecified miliseconds and nano seconds.
8
boolean isAlive() To checks a thread is alive or not.
9
String getName() Returns the name of the thread.
10
setName(String name) Used to set the name of thread.
11
int getPriority() Get the priority of the thread.
12
void setPriority(int priority) Set the priority of thread.
13
static Thread currentThread() Returns the reference of currently executing thread
14
long getId() Returns the id of the thread.
15
static void yield() Temporarily pause the currently executing thread and allow other threads to execute.
16
void suspend() Used to suspend the thread.
17
void resume() Used to resume the suspended thread.
18
void stop() Used to stop the thread.
19
void interrupt() Interrupts the thread.
20
boolead isInterrupted() Check whether the thead is interrupted or not