7 Thread
7 Thread
Fundamentals
A multithreaded program contain two or
more parts that can run concurrently.
Each part of such a program is called thread.
There are two kinds of multitasking
Process-based multitasking
Thread-based multitasking
Process-based multitasking allows you to run
two or more program concurrently.
In thread-based multitasking a single
program can perform two or more task
simultaneously.
Life Cycle of a Thread
Born
start
Ready
thread dispatch
quantum expiration (assign a processor)
yield
timeout expires
I/O completes
interrupt
notifyAll
interrupt
acquire lock
notify
en
Running te
r
iss stasyn
re ue te chr
qu I/ m on
en iz
com
es O
t t t ed
p
i
ee
wa
ple
sl
te
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
Thread.MAX_PRIORITY Priority 10 A B
Priority 9 C
Priority 8
Priority 7 D E F
Priority 6 G
Thread.NORM_PRIORITY Priority 5 H I
Priority 4
Priority 3
Priority 2 J K
Thread.MIN_PRIORITY Priority 1
Thread Priorities
To set the thread’s priority, use the setPriority()
method, which is a member of Thread class
final void setPriority(int level)
level specifies the new priority setting for the calling threads.
To obtain current priority of a thread, use
getPriority() method
final int getPriority()
class clicker implements Runnable {
int click = 0;
Thread t;
private volatile boolean running = true;
public clicker(int p) {
t = new Thread(this); public void stop() {
t.setPriority(p); running = false;
} }
lo.start();
hi.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
lo.stop();
hi.stop();
// Wait for child threads to terminate.
try {
hi.t.join();
lo.t.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
Output:
Low-priority thread: 14441978
(Higher value of click
High-priority thread: 159406749 indicates higher priority)
Synchronization
When two or more threads need to access to
a shared resource, it needs to ensure that the
shared resource is accessed by only one
thread at a time.
Java uses the concept of monitor/semaphore
Is an object that is used as a mutually exclusive
lock or mutex.
Only one thread can own a monitor a given time.
When a thread acquire a lock, all other threads
attempting to enter the locked monitor will be
suspended until the first thread exists the monitor.
Using Synchronized methods
class SharedArea{
String str="";
synchronized void putSharedArea(String s)
{
str=str+"["+s;
try{
Thread.sleep(1000);
}catch(InterruptedException e)
{
System.out.println("Interrupted");
}
str=str+"] ";
}
void show()
{
System.out.println(str);
}
}
class Caller implements Runnable { class Synch {
public static void main(String args[]) {
String msg;
SharedArea target=new SharedArea();
SharedArea targ; Caller ob1 = new Caller(target,"Hello");
Thread t; Caller ob2 = new
Caller(target,"Synchronized");
public Caller(SharedArea Caller ob3 = new Caller(target,"World");
targ,String s) {
msg = s; // wait for threads to end
this.targ=targ; try {
t = new Thread(this); ob1.t.join();
t.start(); ob2.t.join();
ob3.t.join();
}
} catch(InterruptedException e) {
System.out.println("Interrupted");
public void run() { }
targ.putSharedArea(msg); target.show();
} }
} }
Output:
[Hello[Synchronized[World] ] ]
Output Should be:
[Hello] [Synchronized] [World]
To solve the problem you must somehow
restrict its access to only one thread at a time.
Add synchronized keyword
synchronized void putSharedArea(String s){
Using the synchronized
statement
The general form of synchronized statement:
synchronized( object){
//statements to be synchronized
}
Object is a reference to the object being
synchronized.
void putSharedArea(String s)
{
str=str+"["+s;
try {
Thread.sleep(1000);
}
No Synchronized keyword catch(InterruptedException e) {
System.out.println("Interrupted");
}
str=str+"] ";
}
class Q{
int head=0,tail=0;
int qu[]=new int[50000];
synchronized void push(int k){
qu[head]=k;
System.out.println("Producer: "+"["+head+"]: "+qu[head]);
head++;
}
synchronized void pop(){
System.out.println("Consumer: "+"["+tail+"]: "+qu[tail]);
tail++;
}
}
class Producer implements class Consumer implements Runnable {
Burnable{
Q q;
Random r=new Random(); Consumer(Q q){
Q q; this.q=q;
Producer(Q q){ new Thread(this,"Consumer").start();
this.q=q; }
new Thread(this,"Producer").start();
} public void run(){
while(true)
public void run() {
{ q.pop();
int k; }
while(true){ }
k=r.nextInt(500); }
q.push(k);
}
}
}
Consumer: [0]: 0
class PC { Consumer: [1]: 0
Consumer: [2]: 0
public static void main(String Consumer: [3]: 0
args[]) { Consumer: [4]: 0
Q q=new Q(); Consumer: [5]: 0
Consumer: [6]: 0
new Producer(q); Consumer: [7]: 0
new Consumer(q); Consumer: [8]: 0
Consumer: [9]: 0
}
Consumer: [10]: 0
} Producer: [0]: 42
Consumer: [11]: 0
Producer: [1]: 400
Consumer: [12]: 0
Producer: [2]: 181
Consumer: [13]: 0
Producer: [3]: 74
Corrected Example
import java.util.Random;
class Q{
int head=0,tail=0;
int qu[]=new int[50000];
boolean ispush=false;
synchronized void push(int k){
if(ispush) {
try{
wait();
}
catch(InterruptedException e) {
System.out.println("Push Interrupted!");
}
}
ispush=true;
qu[head]=k;
System.out.println("Producer: "+"["+head+"]"+qu[head]);
head++;
notify();
}
synchronized void pop(){
if(!ispush) {
try{
wait();
}
catch(InterruptedException e){
System.out.println("Pop Interrupted!");
}
}
ispush=false;
System.out.println("Consumer: "+"["+tail+"]"+qu[tail]);
tail++;
notify();
}
}
class Producer implements class Consumer implements Runnable{
Runnable{ Q q;
Random r=new Random(); Consumer(Q q){
Q q; this.q=q;
Producer(Q q){ new
this.q=q; Thread(this,"Consumer").start();
new Thread(this,"Producer").start(); }
}
public void run(){
public void run() while(true)
{ {
int k; q.pop();
while(true) }
{ }
k=r.nextInt(500); }
q.push(k);
}
}
}
class FixPC{
Producer: [0]: 2
public static void main(String args[]) {
Consumer: [0]: 2
Producer: [1]: 295
Q q=new Q();
Consumer: [1]: 295
new Producer(q);
Producer: [2]: 404
new Consumer(q);
Consumer: [2]: 404
}
Producer: [3]: 319
}
Consumer: [3]: 319
Producer: [4]: 105
Consumer: [4]: 105
Producer: [5]: 197
Consumer: [5]:197
Producer: [6]: 209
Consumer: [6]: 209
Producer: [7]: 169
Consumer: [7]: 169