0% found this document useful (0 votes)
59 views

Unit 6

This document discusses multithreading in Java. It explains that multithreading allows a computer to perform multiple tasks simultaneously by switching between threads quickly. Creating threads in Java involves defining a class that implements the Runnable interface and overriding the run method. Threads can be in different states like new, runnable, blocked, and terminated. Thread groups allow grouping related threads together.

Uploaded by

api-3749362
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

Unit 6

This document discusses multithreading in Java. It explains that multithreading allows a computer to perform multiple tasks simultaneously by switching between threads quickly. Creating threads in Java involves defining a class that implements the Runnable interface and overriding the run method. Threads can be in different states like new, runnable, blocked, and terminated. Thread groups allow grouping related threads together.

Uploaded by

api-3749362
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 30

Multithreading in

Java
Prepared By:
Munir Ahmad

1
Problem
 Multiple tasks for computer
 Draw & display images on screen
 Check keyboard & mouse input

 Send & receive data on network

 Read & write files to disk

 Perform useful computation (editor, browser, game)

 How does computer do everything at once?


 Multitasking

 Multiprocessing

2
Multitasking (Time-Sharing)
 Approach
 Computer does some work on a task
 Computer then quickly switch to next task

 Tasks managed by operating system (scheduler)

 Computer seems to work on tasks concurrently


 Can improve performance by reducing waiting

3
Multitasking Can Aid Performance
 Single task

 Two tasks

4
Multiprocessing (Multithreading)
 Approach
 Multipleprocessing units (multiprocessor)
 Computer works on several tasks in parallel

 Performance can be improved

Dual-core AMD 32 processor 4096 processor


Athlon X2 Pentium Xeon Cray X1
5
Perform Multiple Tasks Using…
 Thread
 Definition– sequentially executed stream of instructions
 Shares address space with other threads

 Has own execution context


 Program counter, call stack (local variables)
 Communicate via shared access to data
 Multiple threads in process execute same program

 Also known as “lightweight process”

6
Motivation for Multithreading
 Captures logical structure of problem
 May have concurrent interacting components
 Can handle each component using separate thread

 Simplifies programming for problem

 Example

Web Server uses Multiple simultaneous


threads to handle … web browser requests7
Motivation for Multithreading
 Better utilize hardware resources
 When a thread is delayed, compute other threads
 Given extra hardware, compute threads in parallel

 Reduce overall execution time

 Example

Multiple simultaneous Handled faster by


web browser requests… multiple web servers8
Multithreading Overview
 Motivation & background
 Threads
 Creating Java threads
 Thread states

 Scheduling

 Synchronization
 Data races
 Locks

 Wait / Notify

9
Creating Threads in Java
 You have to specify the work you want the thread to
do
 Define a class that implements the Runnable
interface
 public interface Runnable {
 public void run();
}

 Put the work in the run method


 Create an instance of the worker class and create a
thread to run it
 or hand the worker instance to an executor 10
Thread Class
 public class Thread {

 public Thread(Runnable R); // Thread ⇒ R.run()


 public Thread(Runnable R, String name);

 public void start(); // begin thread execution


 ...
}

11
More Thread Class Methods
 public class Thread {
 …
 public String getName();
 public void interrupt();
 public boolean isAlive();
 public void join();
 public void setDaemon(boolean on);
 public void setName(String name);
 public void setPriority(int level);

 public static Thread currentThread(); 12


Creating Threads in Java
 Runnable interface
 Create object implementing Runnable interface
 Pass it to Thread object via Thread constructor
 Example
 public class MyT implements Runnable {
 public void run() {
 … // work for thread
 }
 }
 Thread t = new Thread(new MyT()); // create thread
 t.start(); // begin running thread
 … // thread executing in parallel
13
Alternative (Not Recommended)
 Directly extend Thread class
 public class MyT extends Thread {
 public void run() {
 … // work for thread
 }
}

 MyT t = new MyT(); // create thread


 t.start(); // begin running thread

14
Why not recommended?
 Not a big problem for getting started
 but a bad habit for industrial strength development

 The methods of the worker class and the Thread


class get all tangled up

 Makes it hard to migrate to Thread Pools and other


more efficient approaches

15
Threads – Thread States
 Java thread can be in one of these states
 New – thread allocated & waiting for start()
 Runnable – thread can execute
 Blocked – thread waiting for event (I/O, etc.)
 Terminated – thread finished
 Transitions between states caused by
 Invoking methods in class Thread
 start(), yield(), sleep()
 Other (external) events
 Scheduler, I/O, returning from run()…
16
Threads – Thread States
 State diagram

new start
IO complete,
new runnable
sleep expired,
join complete,
terminate acquire lock

blocked
IO, sleep, join,
request lock
terminated

17
Java Thread Example
 public class ThreadExample implements Runnable {
 public void run() {
 for (int i = 0; i < 3; i++)
 System.out.println(i);

 }
 public static void main(String[] args) {
 new Thread(new ThreadExample()).start();
 new Thread( new ThreadExample()).start();
 System.out.println("Done");
 } 18

}
Java Thread Example – Output
 Possible outputs
 0,1,2,0,1,2,Done // thread 1, thread 2, main()
 0,1,2,Done,0,1,2 // thread 1, main(), thread 2
 Done,0,1,2,0,1,2 // main(), thread 1, thread 2
 0,0,1,1,2,Done,2 // main() & threads interleaved

main (): thread 1, thread 2, println Done

thread 1: println 0, println 1, println 2

thread 2: println 0, println 1, println 2


19
Daemon Threads
 Why doesn’t the program quit as soon as Done is
printed?
 Java threads types
 User

 Daemon
 Provide general services
 Typically never terminate

 Call setDaemon() before start()

 Program termination
 If all non-daemon threads terminate, JVM shuts down
20
Thread Groups
 Sometimes it is useful to identify various threads
oas belonging to a thread group
 ThreadGroup is a class
 At constructor time the group is given a unique name
via a string argument
 Parent threads and child threads

 class ThreadGroup provides tow constructors


• public ThreadGroup (String stringName)
• public ThreadGroup (ThreadGroup
parentThreadGroup, String stringName)
21
Thread Groups cont…
 class ThreadGroup provides three constructors tha
enable the programmer to instantiate a Thread and
associate it with a ThreadGroup
• public Thread (ThreadGroup threadGroup, String
stringName)
• public Thread (ThreadGroup threadGroup, Runnab
runnableObject)
•public Thread (ThreadGroup threadGroup, Runnabl
runnableObject, String stringName)

22
Thread Groups Methods
 activeCount reports the number of active
threads in a thread group plus the number of
active threads in all its child thread groups
 getMaxPriority
setMaxPriority
getName
getParent

23
THANKS

Question & Answers

24
25
26
27
28
29
30

You might also like