Multithreaded Programming
Multithreaded Programming
Multithreaded Programming:
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.
Multitasking
Process-based Thread-based
UNIT-III 2
Process and Thread:
Process Thread
– Definition – executable – Definition – sequentially
program loaded in executed stream of
memory instructions
– Has own address space – Shares address space with
• Variables & data other threads
structures (in memory) – Has own execution context
– Each process may • Program counter, call
execute a different stack (local variables)
program – Communicate via shared
– Communicate via access to data
operating system, files, – Multiple threads in process
network execute same program
– May contain multiple – Also known as “lightweight
threads process”
3
UNIT-III 3
The Java Thread Model:
Thread states
Runnable
Synchronization
Messaging
UNIT-III 4
Thread States:
new start
IO complete,
new running
sleep expired,
join complete,
terminate acquire lock
blocked
IO, sleep, join,
request lock
terminated
5
UNIT-III 5
The Main Thread:
class MainThreadDemo
{
public static void main(String args[ ]) {
Thread t=Thread.currentThread( );
System.out.println("CurrentThread:"+t);
t.setName("CSE");
System.out.println("CurrentThread:"+t); Methods in Thread:
try {
for(int i=1;i<=10;i++) { currentThread
System.out.println("MainThread:"+i); setName
Thread.sleep(500);
} getName
} sleep
catch(InterruptedException e) {
System.out.println(e);
}
System.out.println("Exiting MainThread");
}
}
UNIT-III 6
The Main Thread:
7
UNIT-III 7
Creating a Thread:
UNIT-III 8
Implement the Runnable interface:
UNIT-III 9
Implement the Runnable interface: Example program1
11
UNIT-III 11
Implement the Runnable interface: Example program2
class NewThread implements Runnable class RunnableDemo
{ {
Thread t; public static void main(String args[ ])
NewThread( ) { {
t=new Thread(this,"FirstThread"); NewThread nt1=new NewThread( );
System.out.println("Thread:"+t); nt1.t.start();
} try
public void run( ) { {
try { for(int i=1;i<=10;i++)
for(int i=1;i<=10;i++) {
{ System.out.println("MainThread:"+i);
System.out.println(“NT:"+i); Thread.sleep(500);
Thread.sleep(500); }
} }
} catch(InterruptedException e)
catch(InterruptedException e) { {
System.out.println(e); System.out.println(e);
} }
System.out.println("Exiting NT"); System.out.println("Exiting MainThread");
} }
} }
UNIT-III 12
Implement the Runnable interface: Example program2
13
UNIT-III 13
Extend Thread class:
UNIT-III 14
Example:
class ThreadDemo
class NewThread extends Thread {
{ public static void main(String args[ ])
public void run( ) {
{ NewThread nt1=new NewThread( );
try nt1.start( );
{ try
for(int i=1;i<=10;i++) {
{ for(int i=1;i<=10;i++)
System.out.println("NT:"+i); {
Thread.sleep(500); System.out.println("MainThrd:"+i);
} Thread.sleep(500);
} }
catch(InterruptedException e) }
{ catch(InterruptedException e)
System.out.println(e); {
} System.out.println(e);
System.out.println("Exiting NT"); }
} System.out.println("Exiting MainThrd");
} }
}
UNIT-III 15
Multiple Threads:
class NewThread class MultiThreadDemo {
implements Runnable { public static void main(String args[ ]) {
Thread t; NewThread nt1=new NewThread("First");
NewThread(String name) { NewThread nt2=new NewThread("Second");
t=new Thread(this,name); NewThread nt3=new NewThread("Third");
System.out.println("Thread:"+t); nt1.t.start();
} nt2.t.start();
public void run( ) { nt3.t.start();
try { try {
for(int i=1;i<=10;i++) for(int i=1;i<=10;i++)
{ {
System.out.println("NewThread:"+ System.out.println("MainThread:"+
Thread.currentThread().getName( )+i); Thread.currentThread( ).getName( )+i);
Thread.sleep(500); Thread.sleep(500);
} }
} }
catch(InterruptedException e) { catch(InterruptedException e)
System.out.println(e); {
} System.out.println(e);
System.out.println(“Exiting”+ }
Thread.currentThread( )); System.out.println("Exiting MainThread");
} }
UNIT-III 16
} }
Methods in Thread class:
UNIT-III 18
Synchronized methods:
All objects have their own implicit monitor associated with them.
While a thread is inside a monitor, all threads that try to call this or any
other synchronized method on this object have to wait.
UNIT-III 19
Synchronized statements:
Consider a class was not created by you, but by a third party, and you
do not have access to the source code. Thus, you can’t add
synchronized to the appropriate methods within the class.
You simply put calls to the methods defined by this class inside a
synchronized block.
synchronized(object)
{
// statements to be synchronized
UNIT-III 20
Example: public void run()
class Callme {
{ target.call(msg);
void call(String msg) }}
{ class RunnableDemo
System.out.print("[" + msg); {
try public static void main(String args[])
{ {
Thread.sleep(1000); Callme target = new Callme();
} catch(InterruptedException e) Caller ob1 = new Caller(target, "Hello");
{ Caller ob2 = new Caller(target,
System.out.println("Interrupted"); "Synchronized");
} System.out.println("]"); } } Caller ob3 = new Caller(target, "World");
class Caller implements Runnable try
{ {
String msg; ob1.t.join();
Callme target; ob2.t.join();
Thread t; ob3.t.join();
public Caller(Callme targ, String s) }
{ target = targ; catch(InterruptedException e)
msg = s; {
t = new Thread(this); System.out.println("Interrupted");
t.start(); } } }}
UNIT-III 21
Synchronization example: public void run()
class Callme {
{ target.call(msg);
synchronized void call(String msg) }}
{ class SynchronizationDemo2
System.out.print("[" + msg); {
try public static void main(String args[])
{ {
Thread.sleep(1000); Callme target = new Callme();
} catch(InterruptedException e) Caller ob1 = new Caller(target, "Hello");
{ Caller ob2 = new Caller(target,
System.out.println("Interrupted"); "Synchronized");
} System.out.println("]"); } } Caller ob3 = new Caller(target, "World");
class Caller implements Runnable try
{ {
String msg; ob1.t.join();
Callme target; ob2.t.join();
Thread t; ob3.t.join();
public Caller(Callme targ, String s) }
{ catch(InterruptedException e)
target = targ; {
msg = s; System.out.println("Interrupted");
t = new Thread(this); } } }
UNIT-III 22
t.start(); }
Interthread Communication:
All three methods can be called only from within a synchronized context.
wait( ) tells the calling thread to give up the monitor and go to sleep until
some other thread enters the same monitor and calls notify( ).
notify( ) wakes up the first thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same
object. The highest priority thread will run first.
UNIT-III 23
example: class Producer implements Runnable
{
Q q;
Producer(Q q)
class Q {
{ this.q = q;
int n; new Thread(this, "Producer").start();
synchronized int get() }
{ public void run()
System.out.println("Got: " + n); {
return n; } int i = 0;
synchronized void put(int a) while(true)
{ {
n = a; q.put(i++);
System.out.println("Put: " + n); }} try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println("Exception caught");
} } } }
UNIT-III 24
Example cont:
UNIT-III 25
Example program
26
UNIT-III 26
Example using wait(), notify():
class Q
{
synchronized void put(int a)
int n;
{
boolean valueSet = false;
if(valueSet)
synchronized int get()
try
{
{
if(!valueSet)
wait();
try
}
{
catch(InterruptedException e)
wait();
{
}
System.out.println("InterruptedException
catch(InterruptedException e)
caught");
{
}
n = a;
System.out.println("InterruptedException
valueSet = true;
caught");
System.out.println("Put: " + n);
}
notify();
System.out.println("Got: " + n);
}
valueSet = false;
}
notify();
return n;
} UNIT-III 27
Example cont using wait(), notify(): :
class Producer implements Runnable class Consumer implements Runnable
{ {
Q q; Q q;
Producer(Q q) Consumer(Q q)
{ {
this.q = q; this.q = q;
new Thread(this, "Producer").start(); new Thread(this, "Consumer").start();
} }
public void run() public void run()
{ {
int i = 0; while(true)
while(true) {
{ q.get(); } }}
q.put(i++); class PC2
try {
{ public static void main(String args[])
Thread.sleep(500); {
} Q q = new Q();
catch(InterruptedException e) new Producer(q);
{ new Consumer(q);
System.out.println("Exception System.out.println("Press Control-C to
caught"); } } }} stop.");
UNIT-III }} 28
Example program using wait(), notify():
29
UNIT-III 29
Deadlock:
A a1 A a1
B b1
First
Thread t Second B b1
Thread
run( ) Thread Thread t
run( )
{ {
a1.m1(b1); b1.m3(a1);
} }
UNIT-III 32
Deadlock Example:
33
UNIT-III 33
Thread class:
Constructors:
Thread()
Thread(Runnable target)
Thread(Runnable target, String name)
Thread(String name)
Thread(ThreadGroup group, Runnable target)
UNIT-III 34
ThreadGroups:
Threads are organized into thread groups.
A thread group is simply a related collection of threads.
ThreadGroups can be shown in a hierarchical manner.
There is only one root ThreadGroup that contains all other threads and
groups and each subgroup can contain other groups and threads.
UNIT-III 35
Daemon Threads:
In Java, any thread can be a Daemon thread.
Daemon threads are like a service providers for other threads or
objects running in the same process as the daemon thread.
Daemon threads are used for background supporting tasks and are only
needed while normal threads are executing.
If normal threads are not running and remaining threads are daemon
threads then the interpreter(JVM) exits.
setDaemon (true/false)
UNIT-III 36
Daemon Threads: Example program
class NewThread implements Runnable class DaemonDemo
{ {
Thread t; public static void main(String args[ ])
NewThread( ) { {
t=new Thread(this,"FirstThread"); NewThread nt1=new NewThread( );
System.out.println("Thread:"+t); nt1.t.setDaemon(true);
} nt1.t.start();
public void run( ) { try
try { {
for(int i=1;i<=100;i++) for(int i=1;i<=10;i++)
{ {
System.out.println(“NT:"+i); System.out.println("MainThread:"+i);
Thread.sleep(500); Thread.sleep(500);
} }
} }
catch(InterruptedException e) { catch(InterruptedException e)
System.out.println(e); {
} System.out.println(e);
System.out.println("Exiting NT"); }
} System.out.println("Exiting MainThread");
} }
UNIT-III 37
}
Daemon Threads: Example program Output
UNIT-III 38