0% found this document useful (0 votes)
48 views25 pages

Threads & Timers: CSE219, Computer Science III Stony Brook University

The document discusses multi-threading and how operating systems and programs perform multi-tasking. It explains that when a program has multiple threads, the operating system's thread scheduler determines which threads run in what order. It provides examples of defining your own threads by extending the Thread class and overriding the run() method. The key methods for threads are start(), which makes a thread runnable and calls run(), and run(), which contains the code for the thread's task.

Uploaded by

Sheyla Cárdenas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views25 pages

Threads & Timers: CSE219, Computer Science III Stony Brook University

The document discusses multi-threading and how operating systems and programs perform multi-tasking. It explains that when a program has multiple threads, the operating system's thread scheduler determines which threads run in what order. It provides examples of defining your own threads by extending the Thread class and overriding the run() method. The key methods for threads are start(), which makes a thread runnable and calls run(), and run(), which contains the code for the thread's task.

Uploaded by

Sheyla Cárdenas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Threads & Timers

CSE219, Computer Science III


Stony Brook University
Multi-tasking
• When you’re working, how many different
applications do you have open at one time?
Many! ~100 even if you have only a few visible.

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

— Not yet started


— Not yet known to thread scheduler
— Not runnable

12
(c) Paul Fodor & Pearson Inc.
new – to – runnable Transition
— Constructed thread is started new

—call start method on it start

— Can be scheduled!

— There may be many threads in


runnable
this state.

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

— A dead thread is just dead. dead

— Call isAlive to take a pulse


16
(c) Paul Fodor & Pearson Inc.
Defining your own threads
public class MyThread extends Thread {
...
public void run() {
// task to do when
// the thread is started
}
}
— Create a new thread:
MyThread mT = new MyThread();
— Run the thread:
mT.start();
17
(c) Paul Fodor & Pearson Inc.
The Thread Class
«interface»
java.lang.Runnable

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.

• run() may do one thing or many


–via iteration
–it may even exist for the duration of
the program
20
(c) Paul Fodor & Pearson Inc.
start vs. run
— The main method has a thread
— We write:
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();

}
• Now we have 2 threads: main and t.
• What about:
public static void main(String[] args) {
MyThread t = new MyThread();
t.run();
}
• Still just 1 thread: t.run() is just a method call!
21
(c) Paul Fodor & Pearson Inc.
start vs. run
public class RandomThread extends Thread {
public void run() {
while (true) {
int num = (int) (Math.random() * 10);
System.out.println("\t\t\t\t" + num);
try { Thread.sleep(10);
} catch(InterruptedException ie) {}
}
} /* An InterruptedException is thrown when a thread is waiting,
sleeping, or otherwise occupied, and the thread is interrupted,
} either before or during the activity. Occasionally a method may
wish to test whether the current thread has been interrupted,
and if so, to immediately throw this exception. E.g.,
if (Thread.interrupted())
throw new InterruptedException();
// Clears interrupted status!
*/

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.

You might also like