Multithreaded Programming in
Java
1
Levels of Parallelism
Code-Granularity
Code Item
Sockets Task i-l Task i Task i+1 Large grain
(task level)
Program
func1 ( ) func2 ( ) func3 ( )
{ { {
.... .... .... Medium grain
Threads .... .... .... (control level)
} } } Function (thread)
a ( 0 ) =.. a ( 1 )=.. a ( 2 )=.. Fine grain
Compilers b ( 0 ) =.. b ( 1 )=.. b ( 2 )=.. (data level)
Loop (Compiler)
CPU + x Load Very fine grain
(multiple issue)
2
With hardware
Multitasking
Process based multitasking
Several independent process executing
simultaneously
Os based concept-advatages for os and not
programs
Download a file,run java program,open browser
3
Multithreading
Thread based multitasking
Same program-simultaneously executing
multiple task where each task is a piece of
independent code
Programmatic level
Word-edit,print,checking
Games-different objects on a platform
Road rash-different bikes/objects
Youtube –download 4 files
4
A single threaded program
class ABC
{
….
begin
public void main(..)
{
body
…
.. end
}
}
5
A Multithreaded Program
Threads may switch or
exchange data/results
A thread provides the
Main Thread
mechanism for running a
task.
Each task is an instance of
start
start the Runnable interface,
start
also called a runnable object.
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
Single-threaded Process Multiplethreaded Process
Threads of
Execution
Single instruction stream Multiple instruction stream
Common
Address Space
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
Client 1 Process Server Process
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]);
} - - - - - - - - - -
}
Cooperative Parallel Synchronized
Threads 15
Example application-Process
Threads in word application
18
Process Vs Threads
Process executables which runs in
separate memory space
Threads small process which shared
memory space within a process
PROCESS
THREAD THREAD
Threads
20
Threads
21
Thread ecology in a java program
started by java from main(String[])
started by main thread
started by B thread
lifetime of C thread
What are Threads?
A piece of code that run in concurrent with other
threads.
Each thread is a statically ordered sequence of
instructions.
Threads are being extensively used express
concurrency on both single and multiprocessors
machines.
Programming a task having multiple threads of
control – Multithreading or Multithreaded
Programming.
23
Java Threads
Java has built in thread support for Multithreading
Synchronization
Thread Scheduling
Inter-Thread Communication:
currentThread start setPriority
yield run getPriority
sleep stop suspend
resume
Java Garbage Collector is a low-priority thread
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);
public void run();
public void start();
...
}
An Overview of the Thread Methods
Thread-related methods
Constructors
Thread() - Creates a thread with an auto-numbered name
of format Thread-1, Thread-2...
Thread( threadName ) - Creates a thread with name
run
Does “work” of a thread – What does this mean?
Can be overridden in subclass of Thread or in Runnable
object (more on interface Runnable elsewhere)
start
Launches thread, then returns to caller
Calls run
Error to call start twice for same thread
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 {
public void run() {
System.out.println(" this thread is running ... ");
}
}
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:
MyThread myObject = new MyThread();
Creating Thread Object:
A Runnable object can be wrapped up into a Thread object
Thread thr1 = new Thread( myObject );
Start Execution:
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
public class Print2GUI extend JTextArea implement Runnable {
public void run() {
for (int b = -128; b < 128; b++) append( Integer.toString(b) + “\n” ); }
}
34
A Program with Three Java Threads
Write a program that creates 3 threads
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);
}
System.out.println("Exit from A");
}
36
class B extends Thread
{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println("\t From ThreadB:
j= "+j);
}
System.out.println("Exit from B");
}
37
class C extends Thread
{
public void run()
{
for(int k=1;k<=5;k++)
{
System.out.println("\t From ThreadC:
k= "+k);
}
System.out.println("Exit from C");
}
38
class ThreadTest
{
public static void main(String args[])
{
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.
Create a class Main.
Input and Output format:
Refer to sample Input and Output for formatting specifications.
Sample input and output:
[All Texts in bold corresponds to the input and rest are output]
Enter Number of Counters :
2
Enter text for counter 1 :
FrequencyCounter
Enter text for counter 2 :
JavaTheCompleteReference
Counter 1 Result :
C:1 F:1 c:1 e:3 n:2 o:1 q:1 r:2 t:1 u:2 y:1
Counter 2 Result :
C:1 J:1 R:1 T:1 a:2 c:1 e:7 f:1 h:1 l:1 m:1 n:1 o:1 p:1 r:1 t:1 v:1
42
Life cycle of A Thread
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
if any other method is invoked at this stage, an exception will be
thrown
Runnable state:
Means thread is ready for execution and waiting for
availability of the processor
Threads will be in queue, processed based on priority
Equal priority threads have been assigned time slots for
execution time-slicing
Relinquish control from one thread to another of same
priority can be given before its turn comes , by using
yield() method yield()
t1 t2 t3 t4
Running Thread Runnable Threads
Running state:
Means that the processor has given its time to the thread
for its execution
Thread runs until the control given to some other thread
Situations when running thread may relinquish its control:
1. Suspended using suspend() method suspend for some
time due to certain reason, but not to kill the thread
suspend()
resume()
. . .
Running Runnable Suspended
2. Sleep(time) thread is out of the queue this time period
Entered when sleep method called
Cannot use processor
Enters ready state after sleep time expires
sleep(t)
after(t)
. . .
Running Runnable Sleeping
3. Wait until some event occurs
Waiting state
Entered when wait called in an object thread is accessing
One waiting thread becomes ready when object calls notify
notifyAll - all waiting threads become ready
wait()
notify()
. . .
Running Runnable Waiting
49
Blocked state/Waiting
Blocked thread is considered “not runnable” but
not dead and fully qualified to run again
Entered from running state
Blocked thread cannot use processor, even if available
Common reason for blocked state - waiting on I/O request
waiting to acquire a monitor lock to enter or re-enter a
synchronized block/method
suspend(),Sleep(),wait(),join()
Dead state
Running thread ends when it completed executing its run() method
Also using stop()
All stages running,runnable,blocked
The life cycle of a Java thread
runnable
get the lock blocked/waiting
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
In Java, each thread is assigned priority, which
affects the order in which it is scheduled for
running. The threads so far had same default
priority (NORM_PRIORITY) and they are served
using FCFS policy.
Java allows users to change priority:
ThreadName.setPriority(intNumber)
MIN_PRIORITY = 1
NORM_PRIORITY=5
MAX_PRIORITY=10
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);
}
System.out.println("Exit from A");
}
class B extends Thread
{
public void run()
{
System.out.println("Thread B started");
for(int j=1;j<=4;j++)
{
System.out.println("\t From ThreadB: j= "+j);
}
System.out.println("Exit from B");
}
57
Thread Priority Example
class C extends Thread
{
public void run()
{
System.out.println("Thread C started");
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);
System.out.println("Started Thread A");
threadA.start();
System.out.println("Started Thread B");
threadB.start();
System.out.println("Started Thread C");
threadC.start();
System.out.println("End of main thread");
} 59