Threads & Timers: CSE219, Computer Science III Stony Brook University
Threads & Timers: CSE219, Computer Science III Stony Brook University
2
(c) Paul Fodor & Pearson Inc.
Multithreaded?
• When you request a Web page. Should
the IE client:
– wait for the page before doing anything else
OR
– do other work while waiting
• like responding to user input/rendering
3
(c) Paul Fodor & Pearson Inc.
OS Multi-tasking
• How many tasks is the OS performing?
• Check the “task manager” …
4
(c) Paul Fodor & Pearson Inc.
OS Multi-tasking
• How many CPUs does your PC have?
5
(c) Paul Fodor & Pearson Inc.
Program Multi-Tasking
Most apps need to do multiple tasks “simultaneously”
For example:
getting user input
printing
Internet browsing
How would you do this?
using threads (that you define), and
using a thread scheduler (that the JVM provides)
6
(c) Paul Fodor & Pearson Inc.
Tools for OS Multi-tasking
Thread scheduling
Time-sharing
Virtual Memory
OS details are not a part of this course
At an even lower level, under the OS,
are the actual processors (chips).
7
(c) Paul Fodor & Pearson Inc.
Multi-Core Complicates Everything
Intel Xeon E7
10+ Cores
20+ Threads
Don’t worry!
Let the OS work it out
8
(c) Paul Fodor & Pearson Inc.
Multi-Core Complicates Everything
Multiple Thread 1
threads
Thread 2
sharing a
Thread 3
single CPU
Multiple Thread 1
threads on
Thread 2
multiple
Thread 3
CPUs
9
(c) Paul Fodor & Pearson Inc.
Threads and the Thread Scheduler
You define your own threads
Extend java.lang.Thread
i.e. tasks
Note: main is its own thread
You make your threads runnable
Without this, a thread cannot be started.
Java's thread scheduler decides order!
10
(c) Paul Fodor & Pearson Inc.
State transitions of a thread
new
start
unblock
thread
blocked
runnable
run
method
block
ends
thread
dead
11
(c) Paul Fodor & Pearson Inc.
new state
A constructed Thread object new
12
(c) Paul Fodor & Pearson Inc.
new – to – runnable Transition
Constructed thread is started new
Can be scheduled!
13
(c) Paul Fodor & Pearson Inc.
runnable – to – blocked Transition
Runnable thread made un-runnable
call sleep method on it (for X milliseconds)
directly or via lock method
Can not be scheduled! blocked
runnable
block
thread
Again, there may be many threads in this state
14
(c) Paul Fodor & Pearson Inc.
blocked – to – runnable Transition
Un-runnable thread made runnable
sleep time expires
and is not renewed
unlock method ensures this
Can be scheduled
unblock
thread
blocked
runnable
15
(c) Paul Fodor & Pearson Inc.
runnable – to – dead Transition
Run method completes
runnable
Cannot be rescheduled run
method
ends
java.lang.Thread
+Thread() Creates a default thread.
+Thread(task: Runnable) Creates a thread for a specified task.
+start(): void Starts the thread that causes the run() method to be invoked by the JVM.
+isAlive(): boolean Tests whether the thread is currently running.
+setPriority(p: int): void Sets priority p (ranging from 1 to 10) for this thread.
+join(): void Waits for this thread to finish.
+sleep(millis: long): void Puts the runnable object to sleep for a specified time in milliseconds.
+yield(): void Causes this thread to temporarily pause and allow other threads to execute.
+interrupt(): void Interrupts this thread.
18
(c) Paul Fodor & Pearson Inc.
The 2 key Thread methods
start()
makes thread runnable
calls the run method
Thread class’ start method already does this
if your class that extends Thread you don’t have to define start
run()
executed when a thread is started (with the method start())
run() is where thread work is done
The Thread superclass’ run method does nothing
if your class extends Thread you must define run()
to specify what work your thread will do
19
(c) Paul Fodor & Pearson Inc.
run()
Method Summary
void run()
When an object implementing interface Runnable is used to
create a thread, starting the thread causes the object's run
method to be called in that separately executing thread.
22
(c) Paul Fodor & Pearson Inc.
start vs. run
import java.util.Calendar;
import java.util.GregorianCalendar;
public class StartTester {
public static void main(String[] args){
RandomThread thread = new RandomThread();
thread.start();
while (true) {
Calendar today = new GregorianCalendar();
long hour = today.get(Calendar.HOUR);
long minute = today.get(Calendar.MINUTE);
long second = today.get(Calendar.SECOND);
System.out.println(hour + ":"
+ minute + ":" + second);
try { Thread.sleep(10);
} catch(InterruptedException ie) {}
}
}
} THIS IS A MULTITHREADED APPLICATION!
23
(c) Paul Fodor & Pearson Inc.
start vs. run
import java.util.Calendar;
import java.util.GregorianCalendar;
public class RunTester {
public static void main(String[] args) {
RandomThread thread = new RandomThread();
thread.run(); // Only this main thread is running
while (true) {
Calendar today = new GregorianCalendar();
long hour = today.get(Calendar.HOUR);
long minute = today.get(Calendar.MINUTE);
long second = today.get(Calendar.SECOND);
System.out.println(hour + ":"
+ minute + ":" + second);
try {
Thread.sleep(10);
} catch (InterruptedException ie) {
}
}
24 }
(c) Paul Fodor & Pearson Inc.
}
Creating Tasks and Threads
java.lang.Runnable TaskClass // Client class
public class Client {
...
// Custom task class public void someMethod() {
public class TaskClass implements Runnable { ...
... // Create an instance of TaskClass
public TaskClass(...) { TaskClass task = new TaskClass(...);
...
} // Create a thread
Thread thread = new Thread(task);
// Implement the run method in Runnable
public void run() { // Start a thread
// Tell system how to run custom thread thread.start();
... ...
} }
... ...
} }
25
(c) Paul Fodor & Pearson Inc.