Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Multithreaded Programming

Oops through java

Uploaded by

vaddivanisri1802
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Multithreaded Programming

Oops through java

Uploaded by

vaddivanisri1802
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

UNIT-III 1

Multithreaded Programming:

Java provides built-in support for 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.

Multithreading is a specialized form of multitasking.

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

Java provides one class and one


interface
Thread Priorities
Thread

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:

Java defines two ways to create a thread:

• Implement the Runnable interface.

• Extend Thread class.

UNIT-III 8
Implement the Runnable interface:

Steps to create thread:


1. Create a class that implements the Runnable interface.
2. Override the method run in that class with the code the new thread has to
run.
3. Create an object of the above class.
4. Instantiate an object of class Thread with the constructor
Thread(Runnable threadObj, String name) here threadObj means object
created in step 3.
5. Now call the start method on the object created in step 4 which will
executes a call to run method.

UNIT-III 9
Implement the Runnable interface: Example program1

class NewThread implements Runnable class RunnableDemo1 {


{ public static void main(String args[ ]) {
public void run( ) NewThread nt1=new NewThread( );
{ Thread t=new Thread(nt1,"FirstThread");
try System.out.println("Thread:"+t);
{ t.start( );
for(int i=1;i<=10;i++) try {
{ for(int i=1;i<=10;i++)
System.out.println("NT:"+i); {
Thread.sleep(500); System.out.println("MainThread:"+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 MainThread");
} }
} }
UNIT-III 10
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:

Steps to create a thread:


• Create a new class that extends Thread.
• Override the method run with the code the new thread has to run.
• Create an instance of the class created in step 1.
• Call the start method with that instance.

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:

Three static final variables


MIN_PRIORITY
NORM_PRIORITY
MAX_PRIORITY
UNIT-III 17
Synchronization:

When several threads need access to a shared resource, they need


some way to ensure that the resource will be used by only one thread at
a time.

This way is called synchronization.

Synchronization uses the concept of monitors:


1) only one thread can enter a monitor at any one time
2) other threads have to wait until the thread exits the monitor

Java implements synchronization in two ways:


through the synchronized methods and
through the synchronized statement.

UNIT-III 18
Synchronized methods:

All objects have their own implicit monitor associated with them.

To enter an object’s monitor, call this object’s synchronized method.

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.

To exit the monitor, it is enough to return from the synchronized method.

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.

This is the general form of the synchronized statement:

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:

To avoid polling, Java includes an elegant interprocess communication


mechanism via the wait( ), notify( ), and notifyAll( ) methods.

These methods are implemented as final methods in Object, so all classes


have them.

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:

class Consumer implements Runnable


{ class PC1
Q q; {
Consumer(Q q) public static void main(String args[])
{ {
this.q = q; Q q = new Q();
new Thread(this, "Consumer").start(); new Producer(q);
} new Consumer(q);
public void run() System.out.println("Press Control-C to
{ stop.");
while(true) }
{ }
q.get();
}
}
}

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);
} }

syn m1( B b1) syn m3(A a1)


{ {
a1 … …
b1
b1.m4( ); a1.m2( );
} }
syn m2( ) syn m4( )
{ {
… …
} UNIT-III
} 30
Deadlock Example: class B
{
class A synchronized void bar(A a)
{ {
synchronized void foo(B b) String name =
{ Thread.currentThread().getName();
String name = System.out.println(name + " entered
Thread.currentThread().getName(); B.bar");
System.out.println(name + " entered try
A.foo"); {
try Thread.sleep(1000);
{ }
Thread.sleep(1000); catch(Exception e)
} catch(Exception e) {
{ System.out.println("B Interrupted");
System.out.println("A Interrupted"); }
} System.out.println(name + " trying to call
System.out.println(name + " trying to A.last()");
call B.last()"); a.last();
b.last(); }
} synchronized void last()
synchronized void last() {
{ System.out.println("Inside A.last"); System.out.println("Inside A.last");31
}} UNIT-III
}}
Deadlock Example:
class Deadlock implements Runnable public void run()
{ {
A a = new A(); b.bar(a); // get lock on b in other thread.
B b = new B(); System.out.println("Back in other thread");
Deadlock() }
{ public static void main(String args[])
{
Thread.currentThread().setName("MainT new Deadlock();
hread"); }
Thread t = new Thread(this, }
"RacingThread");
t.start();
a.foo(b); // get lock on a in this
thread.
System.out.println("Back in main
thread");
}

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)

Thread(ThreadGroup group, Runnable target, String name)

Thread(ThreadGroup group, String name)

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.

Some important methods in ThreadGroup class:


getName( )
getParent( )
activeThreadCount( )
Method in Thread class:
getThreadGroup( )

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.

Some methods in Thread class:

setDaemon (true/false)

public boolean isDaemon( )

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

You might also like