Multithreaded Programming
Multithreaded Programming
Java
1
Levels of Parallelism
Code-Granularity
Code Item
Sockets Task i-l Task i Task i+1 Large grain
(task level)
Program
3
Multithreading
class ABC
{
….
begin
public void main(..)
{
body
…
.. end
}
}
5
A Multithreaded Program
Threads may switch or
exchange data/results
A thread is essentially an
object that facilitates the
execution of a task
Thread A Thread B Thread C
6
Single and Multithreaded Processes
threads are light-weight processes within a process
7
single-threaded vs multithreaded programs
{ A();
newThreads {
{ A(); A1(); A2(); A3();
{ A1(); A2(); A3() };
B1(); B2(); }
{B1(); B2() }
}
}
9
10
MULTI-THREADED
APPLICATIONS
11
Web/Internet Applications:
Serving Many Users Simultaneously
PC client
Internet
Server
Local Area Network
PDA
12
Multithreaded Server: For Serving
Multiple Clients Concurrently
Server
Threads
Internet
Client 2 Process
13
Modern Applications need Threads (ex1):
Editing and Printing documents in background.
Printing Thread
Editing Thread
14
Multithreaded/Parallel File Copy
reader()
{ writer()
- - - - - - - - - - buff[0] {
lock(buff[i]); - - - - - - - - - -
read(src,buff[i]); buff[1] lock(buff[i]);
unlock(buff[i]); write(src,buff[i]);
- - - - - - - - - - unlock(buff[i]);
} - - - - - - - - - -
}
PROCESS
THREAD THREAD
Threads
20
Threads
21
Thread ecology in a java program
started by java from main(String[])
started by B thread
lifetime of C thread
What are Threads?
24
Define and launch a java thread
Each Java Run time thread is encapsulated in a
java.lang.Thread instance.
Two ways to define a thread:
1. Extend the Thread class
2. Implement the Runnable interface :
package java.lang;
public interface Runnable { public void run() ; }
Steps for extending the Thread class:
1. Subclass the Thread class;
2. Override the default Thread method run(), which is the entry point
of the thread, like the main(String[]) method in a java program.
Threading Mechanisms...
Create a class that extends the Thread class
Create a class that implements the Runnable
interface
26
The Thread Class
public class Thread extends Object implements Runnable {
public Thread();
public Thread(String name);
public Thread(Runnable target);
public Thread(Runnable target,
String name);
public Thread(Runnable target,
String name, long stackSize);
28
1st method: Extending Thread class
Threads are implemented as objects that contains
a method called run()
class MyThread extends Thread
{
public void run()
{
// thread body of execution
}
}
Create a thread:
MyThread thr1 = new MyThread();
Start Execution of threads:
thr1.start(); 29
An example
class MyThread extends Thread {
class ThreadEx1 {
public static void main(String [] args ) {
MyThread t = new MyThread();
t.start();
}
}
30
2nd method: Threads by implementing
Runnable interface
class MyThread implements Runnable
{
.....
public void run()
{
// thread body of execution
}
}
Creating Object:
thr1.start(); 31
An example
class MyThread implements Runnable {
public void run() {
System.out.println(" this thread is running ... ");
}
}
class ThreadEx2 {
public static void main(String [] args ) {
Thread t = new Thread(new MyThread());
t.start();
}
}
32
Need for Runnable
// Example:
public class Print2Console extends Thread {
public void run() { // run() is to a thread what main() is to a java program
for (int b = -128; b < 128; b++) out.println(b); }
… // additional methods, fields …
}
Impement the Runnable interface if you need a parent
class:
// by extending JTextArea we can reuse all existing code of JTextArea
35
Three threads example
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("\t From ThreadA: i= "+i);
}
36
class B extends Thread
{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println("\t From ThreadB:
j= "+j);
}
for(int k=1;k<=5;k++)
{
System.out.println("\t From ThreadC:
k= "+k);
}
{
new A().start();
new B().start();
new C().start();
} 39
Run 1
From ThreadA: i= 1
From ThreadA: i= 2
From ThreadA: i= 3
From ThreadA: i= 4
From ThreadA: i= 5
Exit from A
From ThreadC: k= 1
From ThreadC: k= 2
From ThreadC: k= 3
From ThreadC: k= 4
From ThreadC: k= 5
Exit from C
From ThreadB: j= 1
From ThreadB: j= 2
From ThreadB: j= 3
From ThreadB: j= 4
From ThreadB: j= 5
Exit from B
40
Run2
From ThreadA: i= 1
From ThreadA: i= 2
From ThreadA: i= 3
From ThreadA: i= 4
From ThreadA: i= 5
From ThreadC: k= 1
From ThreadC: k= 2
From ThreadC: k= 3
From ThreadC: k= 4
From ThreadC: k= 5
Exit from C
From ThreadB: j= 1
From ThreadB: j= 2
From ThreadB: j= 3
From ThreadB: j= 4
From ThreadB: j= 5
Exit from B
Exit from A
41
You decided to modify the application by using multiple threads to reduce the computation time. For this,
accept the number of counters or threads at the beginning of the problem and get the string for each
counter or thread. Create a thread by extending the Thread class and take the user entered string as
input. Each thread calculates the character frequency for the word assigned to that thread. All the counts
are stored locally in the thread and once all the threads are completed print the character frequency for
each of the threads.
States:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
Thread States: Life Cycle of a Thread
Born state
Thread just created
When start called, enters ready state
Ready state (runnable state)
when start() method is called on the thread object. A thread in
runnable state is scheduled to run by JVM but it may not start
running until it gets CPU cycle.
Running state
System assigns processor to thread (thread begins executing)
When run completes or terminates, enters dead state
Dead state
Thread marked to be removed by system
Entered when run terminates or throws uncaught exception
44
Newborn state:
when we create a thread object , the thread is born
not yet scheduled for running
Only following methods can be used:
1. start()
2. stop()
Newborn
start stop
Runnable
state Dead state
t1 t2 t3 t4
resume()
. . .
after(t)
. . .
wait()
notify()
. . .
start() resume()
new Thread(…)
not-running thread t terminates
(ready) sleep done
o.notify(), o.notifyAll()
interrupt()
(set bit) interrupt()
yield(), or
preempty scheduled
by OS (throw exception)
by OS
o.wait()
sleep(…)
running t.join()
stop(),
terminated run() exits suspend()
normally or blocked by lock
abnormally
public class ThreadDemo extends Thread
{
public void run()
{
System.out.println("Thread is running !!");
}
public static void main(String[] args)
{
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
System.out.println("T1 ==> " + t1.getState());
System.out.println("T2 ==> " + t2.getState());
52
t1.start();
System.out.println("T1 ==> " + t1.getState());
System.out.println("T2 ==> " + t2.getState());
t2.start();
System.out.println("T1 ==> " + t1.getState());
System.out.println("T2 ==> " + t2.getState()); } }
53
1 ==> NEW
T2 ==> NEW
T1 ==> RUNNABLE
T2 ==> NEW
T1 ==> RUNNABLE
T2 ==> RUNNABLE
Thread is running !!
Thread is running !! 54
isAlive()
TwoThreadAlive tt = new TwoThreadAlive();
tt.setName("Thread"); System.out.println("before
start(), tt.isAlive()=" + tt.isAlive());
tt.start();
System.out.println("just after start(), tt.isAlive()="
+ tt.isAlive());
55
Thread Priority
56
Thread Priority Example
class A extends Thread
{
public void run()
{
System.out.println("Thread A started");
for(int i=1;i<=4;i++)
{
System.out.println("\t From ThreadA: i= "+i);
}
for(int j=1;j<=4;j++)
{
System.out.println("\t From ThreadB: j= "+j);
}
for(int k=1;k<=4;k++)
{
System.out.println("\t From ThreadC: k=
"+k);
}
System.out.println("Exit from C");
} 58
class ThreadPriority
{
public static void main(String args[])
{
A threadA=new A();
B threadB=new B();
C threadC=new C();
threadC.setPriority(Thread.MAX_PRIORITY);
threadB.setPriority(threadA.getPriority()+1);
threadA.setPriority(Thread.MIN_PRIORITY);