SlideShare a Scribd company logo
Topic 12: Multithreading
Volume II,Chapter 1
Advanced Programming Techniques
Outline
• Introduction: Why and what
• Basics: creating and running threads
• Issues
– Thread states
– Thread scheduling
– Synchronization
– Suspending and stopping threads
• Uses
– Animation
– Threads and Swing
Introduction
• Consider the program Bounce.java
– Desired effects
• If the Start button is clicked, a ball starts to
bounce.
• If the button is clicked again, a second ball
starts to bounce and so on.
• If the Close button is clicked, the windows
closes and the program terminates
– Classes
• Ball
• BallCanvas extends JPanel
• BounceFrame
• Bounce
Introduction
– Classes
• Ball
– public void draw(Graphics2D g2)
» Draws the ball at its current position
– public void move()
» Moves the ball to the next position, reversing direction if it hits one of
the edges
» Request paint afterwards to update UI
• class BallCanvas extends JPanel
– Keeps a list of balls
– public void add(Ball b)
» Add a ball to the canvas.
– public void paintComponent(Graphics g)
» Draw all balls at their current positions
Introduction
– Classes
• class BounceFrame extends JFrame
– Set up GUI and listeners
– When the Close button is clicked this method is called,
public void actionPerformed(ActionEvent evt)
{
System.exit(0);
}
– When the Start Button is clicked, this method is called
public void actionPerformed(ActionEvent evt)
{
addBall(); // Creates and adds a bouncing ball to the canvas
// and make it bounce 1,000 times.
}
Introduction
public void addBall()
{ try {
Ball b = new Ball(canvas); // create a ball
canvas.add(b); // add it to the canvas
// bounce it 1,000 times
for (int i = 1; i <= 1000; i++)
{
b.move();
Thread.sleep(5); // sleep for 5 milliseconds
}}
catch (InterruptedException exception){}
}
Note: sleep is a static method that puts the currently running thread to sleep. It
throws InterruptedException when interrupted.
Introduction
• However
– Cannot start a second ball before the current ball
finishes bouncing
– Cannot terminate program before the current ball
finishes bouncing
– Actually, won’t even work if repaint is used (as it
should be) instead of paint (see end of
Bounce.java)!!!!!
Introduction
Why?
There is a single thread of control.
Actions are executed one by one.
Cannot execute next action before current action finishes
Implications in general:
Cannot do anything else while waiting data from the net.
Cannot stop downloading even though you know, after seeing
part of the download, that you don’t want the download any more
Solution: Multithreading
Introduction
• A multithreaded program has multiple threads of control
– OS runs one thread a short period of time, then switches to another, and so on
– To user, threads appear to run simultaneously. An illusion.
– Nonetheless, makes it easier for user to interact with program
Introduction
In our example, we need more than one thread:
One thread to listen for button clicks
One thread to bounce each ball
//BounceThread.java
Outline
• Introduction: Why and what
• Basics: creating and running threads
• Issues
– Thread states
– Thread scheduling
– Synchronization
– Suspending and stopping threads
• Uses
– Animation
– Threads and Swing
Creating and Running Threads
• How to create and run new threads (from the current thread)?
– Write a class for thread
• Either a class that extends the class java.lang.Thread
class MyThreadClass extends Thread {…}
• Or a class that implements the interface java.lang.Runnable
class MyRunnableClass implements Runnable { ….}
• Specify what the new thread should do in the method void run()
class MyThreadClass extends Thread
{
public void run()
{// codes for new thread to run
}
…}
Creating and Running Threads
• How to create and run new threads?
– Create an object of the thread class
MyThreadClass t = new MyThreadClass();
Thread t = new Thread( new
MyRunnableClass() );
– Start a new thread by calling the start method
t.start()
– Notes:
• Don’t call run directly. “run” does not create new thread
• “start” does thread setup and calls “run”
Creating and Running Threads
• In our example, we want a separate thread to bounce each ball. So we first define this
thread class
class BallThread extends Thread
{
public BallThread(Ball aBall) { b = aBall; }
public void run() // codes for new thread
{ try
{ for (int i = 1; i <= 1000; i++)
{
b.move();
sleep(5);
}}
catch (InterruptedException exception { }
}
private Ball b;
}
Creating and Running Threads
• Next, we modify the addBall method of BounceFrame to
– add a bouncing ball to the canvas and
– start a thread to make it bounce
public void addBall()
{
Ball b = new Ball(canvas);
canvas.add(b);
BallThread thread = new BallThread(b);
thread.start();
}
// BounceThread.java
// try to replace start with run and see what happens
Creating and Running Threads
• Event dispatch thread
– Why?
• In BounceThread.java, the move method calls repaint()
• In Bounce.java, the move method calls paint(canvas.getGraphics());
– Any program starts in the main thread, when the main method is called
– In a GUI program, the main thread creates a window and a event dispatch thread
to handle events. It usually dies thereafter.
– repaint() generates an PaintEvent, which is handled by the event dispatch thread.
• In Bounce.java, the event dispatch thread is consumed by the addBall operation for 5
seconds
• During that time, it cannot handle any events. It does not handle paint event.
• So, the ball would not be painted if repaint() was used instead of paint.
Creating and Running Threads
RunnableTest.java
class RadioButtonDemo extends JPanel
implements Runnable
{ …
public void run ()
{ // display images one by one
}
public void showPicture()
{ if (runner == null)
{ runner = new Thread(this); // create thread
runner.start(); // run thread
}}
private Thread runner;
…}
Invoke the showPicture method
showButton.addActionListener(
new ActionListener()
{
public void actionPerformed( ActionEvent e)
{
showNow = true;
showPicture();
}
}
);
Creating and Running Threads
Outline
• Introduction: Why and what
• Basics: creating and running threads
• Issues
– Thread states
– Thread scheduling
– Synchronization
– Suspending and stopping threads
• Uses
– Animation
– Threads and Swing
Thread States
Four states for threads: new, runnable, blocked, dead
new
start
dead
Note: suspend, resume,stop deprecated.
runnable
run exits
stop
blocked
sleep
done sleeping
suspend
resume
wait notify
block on I/O
I/O complete
Wait for lock
Lock available
Thread States
When a thread has just been created using the new operator, it is in
the new state.
Once start method is invoked (which calls the run method), the
thread becomes runnable.
A runnable thread might not be running.
There can be many runnable threads. But only one of them can be
running at any time point.
OS decides which thread to run. More on this later.
new
runnable
start
Thread States
A runnable thread enters the blocked state when
1. The thread is currently running and method Thread.sleep is called
2. suspend method of the thread is called. (deprecated)
3. The thread calls the wait method.
4. The thread tries to lock an object locked by another thread.
5. The thread calls an operation that is blocked on i/o.
runnable
blocked
sleep
suspend
wait
block on I/O
Wait for lockA blocked
thread cannot
be running
Thread States
A blocked reenters runnable state when
1. It has slept the specified amount of time.
2. resume method of the thread is called. (deprecated)
3. Another method calls notify or notifyAll
4. Object lock released by other thread
5. I/O completed.
runnable
blocked
done sleeping
resume
notify
I/O complete
Lock available
Thread States
A runnable thread enters the dead state when
Its run method exits. Natural death.
stop method of the thread is called. (deprecated)
An exception is thrown but not caught.
dead
runnable
run exits
stop
Thread States
• Finding out states of threads
– Method isAlive allows you to find out whether a
thread is alive of dead.
• This method returns true if the thread is runnable or
blocked,
• false if the thread is still new and not yet runnable or if the
thread is dead
– No way to find out whether an alive thread is running,
runnable, or blocked.
Outline
• Introduction: Why and what
• Basics: creating and running threads
• Issues
– Thread states
– Thread scheduling
– Synchronization
– Suspending and stopping threads
• Uses
– Animation
– Threads and Swing
Thread Scheduling
• At any time, there might be many runnable threads. But only one of them is actually
running.
• The thread scheduler decides which runnable thread to run.
• Questions:
– When does the thread scheduler kick in and pick a thread to run?
– How does the thread scheduler select among the runnable threads?
• A not-so-precise answer:
– A running Java thread will continue to run until
• It calls yield method, or
• It ceases to be runnable (dead or blocked), or
• Another thread with higher priority moves out of blocked state
– Then the thread scheduler kicks in and picks another thread with the highest
priority to run
Thread Scheduling
Two different thread implementations
“Native thread” implementation (e.g. Windows):
Performs time-slicing. Interrupts the running thread periodically to
give other threads a chance to run.
“Green thread” implementation (e.g. Solaris)
Does not perform time-slicing. It keeps a running thread active until
a higher-priority thread awakes and takes control.
Thread Scheduling
The answer on slide 17 is precise for the green thread
implementation.
For the native thread implementation, the precise answer is
A running Java thread will continue to run until
– It calls yield method, or
– It ceases to be runnable (dead or blocked), or
– Another thread with higher priority moves out of blocked state, or
– It is pre-emptied by OS (time-slicing).
Then the thread scheduler kicks in and picks another thread with
the highest priority to run
Thread Scheduling
• Priority of individual threads
– Can be increased or decreased using setPriority
• Java have 10 priority levels (constants of Thread class)
MIN_PRIORITY = 1; NORMAL_PRIORITY = 5;
MAX_PRIORITY = 10
– A thread inherits priority from its parent thread, the one
the creates it.
– Note
• Some OS has fewer. E.g. Windows NT has 7.
• JVM maps Java priority levels to priority level of the underlying OS.
Example: BounceExpress.java
Two kinds of balls: black and red.
Red ball threads have higher priority and hence get more
chance to run. The effect is that red balls appear to be faster.
Thread Scheduling
Thread Scheduling
• The addBall method
public void addBall(int priority, Color
color)
{
Ball b = new Ball(canvas, color);
canvas.add(b);
BallThread thread = new
BallThread(b);
thread.setPriority(priority);
thread.start();
}
Thread Scheduling
• Buttons and listeners
addButton(buttonPanel, "Start",
new ActionListener()
{ public void actionPerformed(ActionEvent evt)
{
addBall(Thread.NORM_PRIORITY, Color.black);
}});
addButton(buttonPanel, "Express",
new ActionListener()
{ public void actionPerformed(ActionEvent evt)
{
addBall(Thread.NORM_PRIORITY + 2, Color.red);
} });
Thread Scheduling
• Question 1:
– Consider the case when there are 1 black ball and 1 red ball.
– When the red-ball thread goes to sleep, there is only one other thread, the
black-ball thread.
– Hence the black-ball thread must be chosen.
– Implication:
• black ball takes one move, red ball takes one move, black ball takes one move, and
so on.
• The two balls should be of the same speed.
– Well, this is not the case. Why?
– There is another thread! What is it? What role does it play?
– When event dispatch thread pauses, the red-ball thread already wake up from
sleep and hence picked by scheduler over back-ball thread.
– (Is pre-emption a reason?)
Thread Scheduling
• Question 2:
– If we change sleeping to 50, red balls are not
faster any more.
– Why?
– In order for the red-ball thread to be picked more
often than the black-ball thread, it must “meet”
the scheduler more often.
– When event dispatch thread pauses, the red-ball
thread is still sleeping, just as the black-ball
thread.
sleep vs. yield
• In BallThread, sleep is called to give other thread a chance to run.
• Another way is to call yield.
class BallThread extends Thread
{
public BallThread(Ball aBall) { b = aBall; }
public void run() // codes for new thread
{ for (int i = 1; i <= 1000; i++)
{
b.move();
yield(); // used to be sleep(5)
}
}
private Ball b;
}
sleep vs. yield
• There is a big difference
– Calling sleep put the current running thread into the
blocked state
– Calling yield does not put the calling thread, t1, into
the blocked state
• It merely let the scheduler kick in and pick another method
to run.
• It might happen that the t1 is select to run again. This
happens when t1 has a higher priority than all other
runnable threads.
BounceExpress1/BounceExpress.java
Thread Scheduling
Cooperating vs. Selfish threads:
A cooperating thread gives others a chance to run
Calling sleep: pause for the specified period of time
Calling yield: pause temporarily. Scheduler kicks in.
A selfish thread does none of this.
Effects of selfish threads are system-dependent:
Green thread: A selfish thread can consume all the CPU time.
Native thread: A selfish thread doesn’t post a big problem.
Thread Scheduling
• BounceSelfish.java
public void run()
{ try
{ for (int i = 1; i <= 1000; i++)
{ b.move();
if (selfish)
{ // busy wait for 5 milliseconds
long t = System.currentTimeMillis();
while (System.currentTimeMillis() < t + 5 ;
}
else sleep(5);
}}
catch (InterruptedException exception){}
}
Thread Scheduling
• Question 3:
– The balls some times jump.
– Why?
– Event dispatch thread does get the time to run.
Paint events accumulate.
Outline
• Introduction: Why and what
• Basics: creating and running threads
• Issues
– Thread states
– Thread scheduling
– Synchronization
– Suspending and stopping threads
• Uses
– Animation
– Threads and Swing
Synchronization
• The Synchronization problem:
Two different threads modify the same object at the same time,
leading to corrupted object. Such a situation is called race
condition.
• An analog:
– You and your partner are finishing a group project and starting
to write the project report.
– The report is kept at a centralized location.
• You open the report and edit it
• Your partner opens the report and edits it
• You save the edits.
• Your partner saves his edits,
– Your edits are lost!
Synchronization
• An example: UnsynchBankTest.java
– class Bank
• A bank with a number of bank accounts.
– class TransferThread extends Thread
• A thread that transfers money from an account to other
accounts in a bank.
– public class UnsynchBankTest
• Create 10 accounts and multiple threads to make random
transfers
Synchronization
• class Bank
public void transfer(int from, int to, int amount)
{ if (accounts[from] < amount) return ;
accounts[from] -= amount;
int tmp = accounts[to];
// added by Instructor so that corruption occurs more easily
try { Thread.sleep(1); }
catch(InterruptedException e) {}
accounts[to] = tmp + amount;
//test: print out total after every 1000 transactions
ntransacts++;
if (ntransacts % 1000 == 0) test();
}
Synchronization
• class TransferThread extends Thread
class TransferThread extends Thread
{ public TransferThread(Bank b, int from, int max)
{…}
public void run()
{ try
{ while (!interrupted())
{ int toAccount = (int)(bank.size() * Math.random());
int amount = (int)(maxAmount * Math.random());
bank.transfer(fromAccount, toAccount, amount);
sleep(1);
}}
catch(InterruptedException e) {}
}
private Bank bank; private int fromAccount; private int maxAmount;
Synchronization
• Class UnsynchBankTest
public static void main(String[] args)
{
Bank b = new Bank(NACCOUNTS, INITIAL_BALANCE);
int i;
for (i = 0; i < NACCOUNTS; i++)
{
TransferThread t = new TransferThread(b, i, INITIAL_BALANCE);
t.setPriority(Thread.NORM_PRIORITY + i % 2);
t.start();
}
}
public static final int NACCOUNTS = 10;
public static final int INITIAL_BALANCE = 10000;
Note: Total amount in all accounts = 100,000
Synchronization
• Run the program
– Very quickly, the amounts in the accounts do not
add up to 100,000
– Why?
• The transfer method of Bank class is not atomic:
consists of many steps
• Can be interrupted in the middle
Synchronization
• Problem scenario:
– Thread 1
• Takes 50 from Account A
• Reads current balance of Account B and stores value in variable tmp
• Goes to sleep (simulate interruption, self interruption)
– Thread 2
• Deposit some fund to Account B
– Thread 1
• Update balance of Account B: tmp + 50
– Result:
• Deposit by Thread 2 is lost!
• The total amount can only be less than 100,000
Synchronization
• Note that even instructions are not atomic.
– Consider the following
accounts[to] += amount;
– It is processed in three steps as follows:
1. Load current value of accounts[to] to a register
2. Add amount
3. Move the result back to accounts[to].
Synchronization
• Execution interruption
accounts[0] is currently 100.
Thread 1 perform
accounts[0] += 50;
Thread 2 performs
accounts[0] += 50;
The correct result should be: accounts[0] == 200.
What is the result if the following happens?
Actual result: accounts[0] == 150
The probability of such interruptions is low (but possible). This
is why we faked interruption using sleep.
Thread 1 Steps 1, 2 Step 3
Thread 2 Steps 1, 2, 3
Synchronization
• How to avoid the work of the transfer method being interrupted?
– In java, the answer is to make the method synchronized.
class Bank
{ …
public synchronized void transfer(int from,
int to,int amount)
{ while (accounts[from] < amount ) {…}
accounts[from] -= amount;
try { Thread.sleep(1); }
catch(InterruptedException e) {}
accounts[to] += amount;
ntransacts++;
if (ntransacts % 1000 == 0) test();
}
}
// SynchronizedBankTest0.java
Synchronization
• How does the mechanism work?
– Object locks
• When a thread calls a synchronized method of an object, the object is locked.
• All other threads that try to call synchronized methods of the object are blocked.
– The thread inside the object can of course call all synchronized methods
– Threads that call unsynchronized methods of the object can proceed.
• When the thread that locked the object finishes or terminates because of uncaught
exception, it relinquishes the object lock
• Periodically, the thread scheduler activates the threads waiting for the lock. They all
become runnable.
• When one of the blocked threads is scheduled to run, it checks to see if the object is
locked. If not, it proceeds and locks the object.
Synchronization
• In the bank example, if a thread is executing b.transfer(…), it locks the
Bank object b.
• While b is locked, other threads trying to call b.transfer(…) are blocked.
• b.transfer(…) is not interrupted.
Synchronization
• When the thread that locks b finishes, it gives up the object lock. The
“door” is again open.
• Periodically, the thread scheduler unblocks all threads waiting for the
object lock
• When such a thread is scheduled to run again, it checks whether b is still
locked. If not, it proceeds and locks b.
• Otherwise, it becomes blocked again.
Synchronization
• Note that SynchronizedBankTest0.java
is much slower than
UnsynchronizedBankTest.java
– Other threads trying to get into an
bank account cannot do so if it is
locked by another thread, even that
thread is sleeping inside!
• Synchronization takes time.
– Reason why not all methods are synchronized.
– In particular, most methods of classes in Swing are not
synchronized.
• Swing is not thread-safe.
Synchronization/wait and notify
• What to do when the from account does not
have sufficient fund?
– Currently, transfer nonetheless
– One possible solution
public synchronized void transfer(int from,
int to, int amount)
{ if (accounts[from] < amount) return ;
– Obviously not good solutions.
Synchronization/wait and notify
• How about this?
public void synchronized transfer(int from, int to,
int amount)
{ while (accounts[from] < amount)
{
try {
Thread.sleep(5);
}catch(InterruptedException e) {}
}
• The idea is
– The balance of the from account might increase after 5 milliseconds
• But does not work:
– A sleeping thread does not relinquishes its object locks
– In the case, no other threads can get in the bank object and make transfers
– Account balances will be the same when the thread wakes up.
Synchronization/wait and notify
• Solution: Call wait instead of sleep.
public synchronized void
transfer(int from, int to, int
amount)
{ while (accounts[from] < amount)
{ try { wait(); }
catch(InterruptedException e)
{}
}
…}
Synchronization/wait and notify
wait
notifyAll
Synchronization/wait and notify
• wait is a method of the Object class. It causes the calling method to wait
(blocked) until notified (when another thread calls notify or notifyAll)
• While waiting, a thread relinquishes its object locks. This gives other thread a chance
to access the object.
• notify or notifyAll are all methods of the Object class.
– notify randomly selects a thread among those waiting for an object lock
(inside the object) and unblocks it.
– notifyAll unblocks all threads waiting for an object lock (inside the object).
Preferred because it reduces the probability of deadlock (Exercise: Why is this?).
• Note: wait, notify and notifyAll should only be called by a thread that is
the owner of this object's monitor (within synchronized method).
Synchronization/wait and notify
• In our example, a thread calls notifyAll when it is done with a object.
public synchronized void transfer(int
from, int to,
int
amount)
{ while (accounts[from] < amount)
{ try { wait(); }
catch(InterruptedException e) {}
}
…
notifyAll();
…}
SynchBankTest.java
Synchronization/Deadlock
Deadlock occurs when a number of threads waiting for
each other
Example:
Account 1: $2,000
Account 2: $3,000
Thread 1: Transfer $3,000 from account 1 to account 2
Thread 2: Transfer $4,000 from account 2 to account 1
It is the responsibility of programmer to avoid
deadlocks.
Outline
• Introduction: Why and what
• Basics: creating and running threads
• Issues
– Thread states
– Thread scheduling
– Synchronization
– Suspending and stopping threads
Stopping and Suspending Threads
The stop method is deprecated because it can corrupt
objects.
Consider a thread that is transferring money from one
account to another.
If the thread is stopped after withdrawal from the first
account and before deposit to the second account, an
error arises.
(Other threads can continue since the stopped thread
releases all locks.)
How to stop a thread safely?
Introduce variable stopRequested and check it in a safe place of
the run method
Public class MyThread extends Thread
{ public void run ()
{ try
{ while ( !stopRequested && more work to do)
{ do more work}
}
catch (InterruptedException e)
{ if (stopRequested ) return;
}
}
public void requestStop()
{ stopRequested = true;
interrupt();
}
private boolean stopRequested = false;
}
To terminate a thread t, call t.requestStop();
Why and how does it work:
If thread t is running and no more work to do, run method returns
naturally. (Natural death).
If t.requestStop() is called,
1. While t is running. The thread will exit the next time it checks
the condition “!stopRequested”. (It will not stop in the middle of
executing a synchronized method and hence does not lead to corrupted
objects.)
2. While t is sleeping or blocked. The thread is interrupted, causing
an InterruptedException. The exception handler will
terminate the thread.
To avoid corrupted objects, make sure that a thread doesn’t sleep
while executing a synchronized method. You should never do this
anyway.
Waiting is no problem because it gives up object lock)
Stopping and Suspending Threads
Stopping and Suspending Threads
The suspend and resume methods are deprecated
because they can easily lead to deadlocks.
(Suspended threads do not release object locks.)
Suppose you suspend a thread t1, and t1 has locked
an object x.
Further suppose t2 is responsible to resume t1 but it
needs to access a synchronized method of x first.
Then, deadlock results.
The resume method is deprecated because suspend is.
How to suspend a thread safely?
Use the wait and notifyAll methods
Suspend by calling wait and resume using notifyAll
1. Write a class so that we can use its objects for locks
public class suspenderRequestor
{ public synchronized void set (boolean b)
{ suspendRequested = b;
notifyAll();}
public synchronized void waiteForResume()
throws InterruptedException
{ while ( suspendRequested) wait (); }
private boolean suspendRequested
}
2. Structure your thread class as follows
public class MyThread extends Thread
{ public void requestSuspend()
{ suspender.set( true ); }
public synchronized void requestResume()
{ suspender.set(false);}
public void run ()
{ while ( more work to do)
{ suspender.waitForResume();// call this once in a while
do more work;
}
}
private SuspendRequestor suspender
= new SuspendRequestor();
}
To suspend and resume a thread t, call
t.requestSuspend(); t.requestResume();
Stopping and Suspending Threads
Why and how does this work?
If t.requestSuspend() is called,
suspender.suspendRequest becomes true.
The next time t calls suspender.waitForResume(), t waits
inside object suspender.
It will resume only when another thread calls
t.requestResume(), which calls suspender.set(true),
which in turn notifies t.
While t is waiting, it releases all object locks. This is different from
suspend.
Outline
• Introduction: Why and what
• Basics: creating and running threads
• Issues
– Thread states
– Thread scheduling
– Synchronization
– Suspending and stopping threads
Animation
• Animation: a separate thread to
sequentially display a sequence of images,
each of which is called a frame.
• Managing images
1. You can put each frame in a separate file, or
2. Put all frames on one file. (See right).
We have studied case1 in
RunnableTest.java.
Animation
• Show one frame of image
public class Animation extends JApplet
{ public void loadImage(URL url)..
{ // size applet to the size of one frame
resize(imageWidth,
imageHeight / imageCount);
}
public void paint(Graphics g)
{
if (image == null) return;
// put this point at the upper-left
// corner of applet
g.drawImage(image, 0,
-(imageHeight/imageCount)
* current, null);
}
… Applet
Animation
• Lunching new thread for showing frames
public class Animation extends JApplet
{ public void start()
{ runner = new Thread()
{ public void run()
{ try
{ while (!Thread.interrupted())
{
repaint();
current = (current + 1) % imageCount;
Thread.sleep(200); }
} catch(InterruptedException e) {}
}};
runner.start();
showStatus("Click to stop");
}
Outline
• Introduction: Why and what
• Basics: creating and running threads
• Issues
– Thread states
– Thread scheduling
– Synchronization
– Suspending and stopping threads
Threads and Swing
Threads in a Swing program:
Main thread: started by main method and usually
exits after displaying frame window.
Event dispatch thread: started when the first window
is shown and stays alive until terminated by user.
Event dispatch thread runs codes for handling events
such as calls to actionPerformed or
paintComponent.
Threads and Swing
From the event dispatch thread, one wants to fire
up threads for
Time-consuming actions
Actions that can be blocked on I/O
Sleeping
Otherwise, GUI might seem dead or frozen.
Threads and Swing
Caution: Swing is not thread safe!
Most methods in Swing classes are not synchronized.
If one tamper with UI components from different threads, UI
might be corrupted.
Single thread rule for Swing programming
Modify UI components only in the event dispatch thread
Other threads should send actions that modify UI components to
the event dispatch thread using the invokeLater or
invokeAndWait methods of the EventQueue class (see
textbook for details.)
//swingThreadTest.java
Summary of classes and methods
• public class Thread extends Object implements Runnable
– Thread() , Thread(Runnable target)
– Constants: MAX_PRIORITY NORMAL_PRIORITY, MIN_PRIORITY
– static: sleep, yield, interrupted
– start, run, setPriority, setPriority, interrupt
– isAlive, isInterrupted
• public interface Runnable
– run
• public class Object
– wait, notify, notifyAll
• public class InterruptedException extends Exception

More Related Content

What's hot

12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
APU
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
parag
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
myrajendra
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 

What's hot (19)

Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 
Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreading
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java threading
Java threadingJava threading
Java threading
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Threads in java
Threads in javaThreads in java
Threads in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Threads
ThreadsThreads
Threads
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
 

Viewers also liked

JavaFX 2.0 - リッチクライアントのためのUI基盤
JavaFX 2.0 - リッチクライアントのためのUI基盤JavaFX 2.0 - リッチクライアントのためのUI基盤
JavaFX 2.0 - リッチクライアントのためのUI基盤
Yuichi Sakuraba
 

Viewers also liked (20)

Java IO
Java IOJava IO
Java IO
 
Gwt jetty et sources de données
Gwt   jetty et sources de donnéesGwt   jetty et sources de données
Gwt jetty et sources de données
 
JavaFX 2.0 - リッチクライアントのためのUI基盤
JavaFX 2.0 - リッチクライアントのためのUI基盤JavaFX 2.0 - リッチクライアントのためのUI基盤
JavaFX 2.0 - リッチクライアントのためのUI基盤
 
Les ateliers android_1_vers2015
Les ateliers android_1_vers2015Les ateliers android_1_vers2015
Les ateliers android_1_vers2015
 
Hacking Tomcat
Hacking TomcatHacking Tomcat
Hacking Tomcat
 
Introduction aux-sockets
Introduction aux-socketsIntroduction aux-sockets
Introduction aux-sockets
 
Formation1 sockets
Formation1 socketsFormation1 sockets
Formation1 sockets
 
Autumn collection JavaOne 2014
Autumn collection JavaOne 2014Autumn collection JavaOne 2014
Autumn collection JavaOne 2014
 
Le Réseau et Java
Le Réseau et JavaLe Réseau et Java
Le Réseau et Java
 
50 new things you can do with java 8
50 new things you can do with java 850 new things you can do with java 8
50 new things you can do with java 8
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
 
Cycle de vie d'activité Android et les composant d'Android
Cycle de vie d'activité Android et les composant d'AndroidCycle de vie d'activité Android et les composant d'Android
Cycle de vie d'activité Android et les composant d'Android
 
Toolbarexample
ToolbarexampleToolbarexample
Toolbarexample
 
Java quick reference v2
Java quick reference v2Java quick reference v2
Java quick reference v2
 
Core java online training
Core java online trainingCore java online training
Core java online training
 
Non ieee dot net projects list
Non  ieee dot net projects list Non  ieee dot net projects list
Non ieee dot net projects list
 
Yaazli International Web Project Workshop
Yaazli International Web Project WorkshopYaazli International Web Project Workshop
Yaazli International Web Project Workshop
 
Savr
SavrSavr
Savr
 
Yaazli International AngularJS 5 Training
Yaazli International AngularJS 5 TrainingYaazli International AngularJS 5 Training
Yaazli International AngularJS 5 Training
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 

Similar to java threads

OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
Arulmozhivarman8
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
ssusere538f7
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming language
arnavytstudio2814
 

Similar to java threads (20)

multithreading, creating a thread and life cycle in java.ppt
multithreading, creating a thread and life cycle in java.pptmultithreading, creating a thread and life cycle in java.ppt
multithreading, creating a thread and life cycle in java.ppt
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in java
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
BCA MultiThreading.ppt
BCA MultiThreading.pptBCA MultiThreading.ppt
BCA MultiThreading.ppt
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming language
 
Thread Concept: Multithreading, Creating thread using thread
Thread Concept: Multithreading, Creating thread using threadThread Concept: Multithreading, Creating thread using thread
Thread Concept: Multithreading, Creating thread using thread
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
 
Slide 7 Thread-1.pptx
Slide 7 Thread-1.pptxSlide 7 Thread-1.pptx
Slide 7 Thread-1.pptx
 

More from Waheed Warraich (12)

java jdbc connection
java jdbc connectionjava jdbc connection
java jdbc connection
 
java networking
 java networking java networking
java networking
 
java applets
java appletsjava applets
java applets
 
java swing
java swingjava swing
java swing
 
09events
09events09events
09events
 
08graphics
08graphics08graphics
08graphics
 
06 exceptions
06 exceptions06 exceptions
06 exceptions
 
05io
05io05io
05io
 
04inherit
04inherit04inherit
04inherit
 
03class
03class03class
03class
 
02basics
02basics02basics
02basics
 
01intro
01intro01intro
01intro
 

Recently uploaded

Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 

Recently uploaded (20)

Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
 
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptBasic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
NLC-2024-Orientation-for-RO-SDO (1).pptx
NLC-2024-Orientation-for-RO-SDO (1).pptxNLC-2024-Orientation-for-RO-SDO (1).pptx
NLC-2024-Orientation-for-RO-SDO (1).pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Extraction Of Natural Dye From Beetroot (Beta Vulgaris) And Preparation Of He...
Extraction Of Natural Dye From Beetroot (Beta Vulgaris) And Preparation Of He...Extraction Of Natural Dye From Beetroot (Beta Vulgaris) And Preparation Of He...
Extraction Of Natural Dye From Beetroot (Beta Vulgaris) And Preparation Of He...
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxJose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 

java threads

  • 1. Topic 12: Multithreading Volume II,Chapter 1 Advanced Programming Techniques
  • 2. Outline • Introduction: Why and what • Basics: creating and running threads • Issues – Thread states – Thread scheduling – Synchronization – Suspending and stopping threads • Uses – Animation – Threads and Swing
  • 3. Introduction • Consider the program Bounce.java – Desired effects • If the Start button is clicked, a ball starts to bounce. • If the button is clicked again, a second ball starts to bounce and so on. • If the Close button is clicked, the windows closes and the program terminates – Classes • Ball • BallCanvas extends JPanel • BounceFrame • Bounce
  • 4. Introduction – Classes • Ball – public void draw(Graphics2D g2) » Draws the ball at its current position – public void move() » Moves the ball to the next position, reversing direction if it hits one of the edges » Request paint afterwards to update UI • class BallCanvas extends JPanel – Keeps a list of balls – public void add(Ball b) » Add a ball to the canvas. – public void paintComponent(Graphics g) » Draw all balls at their current positions
  • 5. Introduction – Classes • class BounceFrame extends JFrame – Set up GUI and listeners – When the Close button is clicked this method is called, public void actionPerformed(ActionEvent evt) { System.exit(0); } – When the Start Button is clicked, this method is called public void actionPerformed(ActionEvent evt) { addBall(); // Creates and adds a bouncing ball to the canvas // and make it bounce 1,000 times. }
  • 6. Introduction public void addBall() { try { Ball b = new Ball(canvas); // create a ball canvas.add(b); // add it to the canvas // bounce it 1,000 times for (int i = 1; i <= 1000; i++) { b.move(); Thread.sleep(5); // sleep for 5 milliseconds }} catch (InterruptedException exception){} } Note: sleep is a static method that puts the currently running thread to sleep. It throws InterruptedException when interrupted.
  • 7. Introduction • However – Cannot start a second ball before the current ball finishes bouncing – Cannot terminate program before the current ball finishes bouncing – Actually, won’t even work if repaint is used (as it should be) instead of paint (see end of Bounce.java)!!!!!
  • 8. Introduction Why? There is a single thread of control. Actions are executed one by one. Cannot execute next action before current action finishes Implications in general: Cannot do anything else while waiting data from the net. Cannot stop downloading even though you know, after seeing part of the download, that you don’t want the download any more Solution: Multithreading
  • 9. Introduction • A multithreaded program has multiple threads of control – OS runs one thread a short period of time, then switches to another, and so on – To user, threads appear to run simultaneously. An illusion. – Nonetheless, makes it easier for user to interact with program
  • 10. Introduction In our example, we need more than one thread: One thread to listen for button clicks One thread to bounce each ball //BounceThread.java
  • 11. Outline • Introduction: Why and what • Basics: creating and running threads • Issues – Thread states – Thread scheduling – Synchronization – Suspending and stopping threads • Uses – Animation – Threads and Swing
  • 12. Creating and Running Threads • How to create and run new threads (from the current thread)? – Write a class for thread • Either a class that extends the class java.lang.Thread class MyThreadClass extends Thread {…} • Or a class that implements the interface java.lang.Runnable class MyRunnableClass implements Runnable { ….} • Specify what the new thread should do in the method void run() class MyThreadClass extends Thread { public void run() {// codes for new thread to run } …}
  • 13. Creating and Running Threads • How to create and run new threads? – Create an object of the thread class MyThreadClass t = new MyThreadClass(); Thread t = new Thread( new MyRunnableClass() ); – Start a new thread by calling the start method t.start() – Notes: • Don’t call run directly. “run” does not create new thread • “start” does thread setup and calls “run”
  • 14. Creating and Running Threads • In our example, we want a separate thread to bounce each ball. So we first define this thread class class BallThread extends Thread { public BallThread(Ball aBall) { b = aBall; } public void run() // codes for new thread { try { for (int i = 1; i <= 1000; i++) { b.move(); sleep(5); }} catch (InterruptedException exception { } } private Ball b; }
  • 15. Creating and Running Threads • Next, we modify the addBall method of BounceFrame to – add a bouncing ball to the canvas and – start a thread to make it bounce public void addBall() { Ball b = new Ball(canvas); canvas.add(b); BallThread thread = new BallThread(b); thread.start(); } // BounceThread.java // try to replace start with run and see what happens
  • 16. Creating and Running Threads • Event dispatch thread – Why? • In BounceThread.java, the move method calls repaint() • In Bounce.java, the move method calls paint(canvas.getGraphics()); – Any program starts in the main thread, when the main method is called – In a GUI program, the main thread creates a window and a event dispatch thread to handle events. It usually dies thereafter. – repaint() generates an PaintEvent, which is handled by the event dispatch thread. • In Bounce.java, the event dispatch thread is consumed by the addBall operation for 5 seconds • During that time, it cannot handle any events. It does not handle paint event. • So, the ball would not be painted if repaint() was used instead of paint.
  • 17. Creating and Running Threads RunnableTest.java class RadioButtonDemo extends JPanel implements Runnable { … public void run () { // display images one by one } public void showPicture() { if (runner == null) { runner = new Thread(this); // create thread runner.start(); // run thread }} private Thread runner; …}
  • 18. Invoke the showPicture method showButton.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e) { showNow = true; showPicture(); } } ); Creating and Running Threads
  • 19. Outline • Introduction: Why and what • Basics: creating and running threads • Issues – Thread states – Thread scheduling – Synchronization – Suspending and stopping threads • Uses – Animation – Threads and Swing
  • 20. Thread States Four states for threads: new, runnable, blocked, dead new start dead Note: suspend, resume,stop deprecated. runnable run exits stop blocked sleep done sleeping suspend resume wait notify block on I/O I/O complete Wait for lock Lock available
  • 21. Thread States When a thread has just been created using the new operator, it is in the new state. Once start method is invoked (which calls the run method), the thread becomes runnable. A runnable thread might not be running. There can be many runnable threads. But only one of them can be running at any time point. OS decides which thread to run. More on this later. new runnable start
  • 22. Thread States A runnable thread enters the blocked state when 1. The thread is currently running and method Thread.sleep is called 2. suspend method of the thread is called. (deprecated) 3. The thread calls the wait method. 4. The thread tries to lock an object locked by another thread. 5. The thread calls an operation that is blocked on i/o. runnable blocked sleep suspend wait block on I/O Wait for lockA blocked thread cannot be running
  • 23. Thread States A blocked reenters runnable state when 1. It has slept the specified amount of time. 2. resume method of the thread is called. (deprecated) 3. Another method calls notify or notifyAll 4. Object lock released by other thread 5. I/O completed. runnable blocked done sleeping resume notify I/O complete Lock available
  • 24. Thread States A runnable thread enters the dead state when Its run method exits. Natural death. stop method of the thread is called. (deprecated) An exception is thrown but not caught. dead runnable run exits stop
  • 25. Thread States • Finding out states of threads – Method isAlive allows you to find out whether a thread is alive of dead. • This method returns true if the thread is runnable or blocked, • false if the thread is still new and not yet runnable or if the thread is dead – No way to find out whether an alive thread is running, runnable, or blocked.
  • 26. Outline • Introduction: Why and what • Basics: creating and running threads • Issues – Thread states – Thread scheduling – Synchronization – Suspending and stopping threads • Uses – Animation – Threads and Swing
  • 27. Thread Scheduling • At any time, there might be many runnable threads. But only one of them is actually running. • The thread scheduler decides which runnable thread to run. • Questions: – When does the thread scheduler kick in and pick a thread to run? – How does the thread scheduler select among the runnable threads? • A not-so-precise answer: – A running Java thread will continue to run until • It calls yield method, or • It ceases to be runnable (dead or blocked), or • Another thread with higher priority moves out of blocked state – Then the thread scheduler kicks in and picks another thread with the highest priority to run
  • 28. Thread Scheduling Two different thread implementations “Native thread” implementation (e.g. Windows): Performs time-slicing. Interrupts the running thread periodically to give other threads a chance to run. “Green thread” implementation (e.g. Solaris) Does not perform time-slicing. It keeps a running thread active until a higher-priority thread awakes and takes control.
  • 29. Thread Scheduling The answer on slide 17 is precise for the green thread implementation. For the native thread implementation, the precise answer is A running Java thread will continue to run until – It calls yield method, or – It ceases to be runnable (dead or blocked), or – Another thread with higher priority moves out of blocked state, or – It is pre-emptied by OS (time-slicing). Then the thread scheduler kicks in and picks another thread with the highest priority to run
  • 30. Thread Scheduling • Priority of individual threads – Can be increased or decreased using setPriority • Java have 10 priority levels (constants of Thread class) MIN_PRIORITY = 1; NORMAL_PRIORITY = 5; MAX_PRIORITY = 10 – A thread inherits priority from its parent thread, the one the creates it. – Note • Some OS has fewer. E.g. Windows NT has 7. • JVM maps Java priority levels to priority level of the underlying OS.
  • 31. Example: BounceExpress.java Two kinds of balls: black and red. Red ball threads have higher priority and hence get more chance to run. The effect is that red balls appear to be faster. Thread Scheduling
  • 32. Thread Scheduling • The addBall method public void addBall(int priority, Color color) { Ball b = new Ball(canvas, color); canvas.add(b); BallThread thread = new BallThread(b); thread.setPriority(priority); thread.start(); }
  • 33. Thread Scheduling • Buttons and listeners addButton(buttonPanel, "Start", new ActionListener() { public void actionPerformed(ActionEvent evt) { addBall(Thread.NORM_PRIORITY, Color.black); }}); addButton(buttonPanel, "Express", new ActionListener() { public void actionPerformed(ActionEvent evt) { addBall(Thread.NORM_PRIORITY + 2, Color.red); } });
  • 34. Thread Scheduling • Question 1: – Consider the case when there are 1 black ball and 1 red ball. – When the red-ball thread goes to sleep, there is only one other thread, the black-ball thread. – Hence the black-ball thread must be chosen. – Implication: • black ball takes one move, red ball takes one move, black ball takes one move, and so on. • The two balls should be of the same speed. – Well, this is not the case. Why? – There is another thread! What is it? What role does it play? – When event dispatch thread pauses, the red-ball thread already wake up from sleep and hence picked by scheduler over back-ball thread. – (Is pre-emption a reason?)
  • 35. Thread Scheduling • Question 2: – If we change sleeping to 50, red balls are not faster any more. – Why? – In order for the red-ball thread to be picked more often than the black-ball thread, it must “meet” the scheduler more often. – When event dispatch thread pauses, the red-ball thread is still sleeping, just as the black-ball thread.
  • 36. sleep vs. yield • In BallThread, sleep is called to give other thread a chance to run. • Another way is to call yield. class BallThread extends Thread { public BallThread(Ball aBall) { b = aBall; } public void run() // codes for new thread { for (int i = 1; i <= 1000; i++) { b.move(); yield(); // used to be sleep(5) } } private Ball b; }
  • 37. sleep vs. yield • There is a big difference – Calling sleep put the current running thread into the blocked state – Calling yield does not put the calling thread, t1, into the blocked state • It merely let the scheduler kick in and pick another method to run. • It might happen that the t1 is select to run again. This happens when t1 has a higher priority than all other runnable threads. BounceExpress1/BounceExpress.java
  • 38. Thread Scheduling Cooperating vs. Selfish threads: A cooperating thread gives others a chance to run Calling sleep: pause for the specified period of time Calling yield: pause temporarily. Scheduler kicks in. A selfish thread does none of this. Effects of selfish threads are system-dependent: Green thread: A selfish thread can consume all the CPU time. Native thread: A selfish thread doesn’t post a big problem.
  • 39. Thread Scheduling • BounceSelfish.java public void run() { try { for (int i = 1; i <= 1000; i++) { b.move(); if (selfish) { // busy wait for 5 milliseconds long t = System.currentTimeMillis(); while (System.currentTimeMillis() < t + 5 ; } else sleep(5); }} catch (InterruptedException exception){} }
  • 40. Thread Scheduling • Question 3: – The balls some times jump. – Why? – Event dispatch thread does get the time to run. Paint events accumulate.
  • 41. Outline • Introduction: Why and what • Basics: creating and running threads • Issues – Thread states – Thread scheduling – Synchronization – Suspending and stopping threads • Uses – Animation – Threads and Swing
  • 42. Synchronization • The Synchronization problem: Two different threads modify the same object at the same time, leading to corrupted object. Such a situation is called race condition. • An analog: – You and your partner are finishing a group project and starting to write the project report. – The report is kept at a centralized location. • You open the report and edit it • Your partner opens the report and edits it • You save the edits. • Your partner saves his edits, – Your edits are lost!
  • 43. Synchronization • An example: UnsynchBankTest.java – class Bank • A bank with a number of bank accounts. – class TransferThread extends Thread • A thread that transfers money from an account to other accounts in a bank. – public class UnsynchBankTest • Create 10 accounts and multiple threads to make random transfers
  • 44. Synchronization • class Bank public void transfer(int from, int to, int amount) { if (accounts[from] < amount) return ; accounts[from] -= amount; int tmp = accounts[to]; // added by Instructor so that corruption occurs more easily try { Thread.sleep(1); } catch(InterruptedException e) {} accounts[to] = tmp + amount; //test: print out total after every 1000 transactions ntransacts++; if (ntransacts % 1000 == 0) test(); }
  • 45. Synchronization • class TransferThread extends Thread class TransferThread extends Thread { public TransferThread(Bank b, int from, int max) {…} public void run() { try { while (!interrupted()) { int toAccount = (int)(bank.size() * Math.random()); int amount = (int)(maxAmount * Math.random()); bank.transfer(fromAccount, toAccount, amount); sleep(1); }} catch(InterruptedException e) {} } private Bank bank; private int fromAccount; private int maxAmount;
  • 46. Synchronization • Class UnsynchBankTest public static void main(String[] args) { Bank b = new Bank(NACCOUNTS, INITIAL_BALANCE); int i; for (i = 0; i < NACCOUNTS; i++) { TransferThread t = new TransferThread(b, i, INITIAL_BALANCE); t.setPriority(Thread.NORM_PRIORITY + i % 2); t.start(); } } public static final int NACCOUNTS = 10; public static final int INITIAL_BALANCE = 10000; Note: Total amount in all accounts = 100,000
  • 47. Synchronization • Run the program – Very quickly, the amounts in the accounts do not add up to 100,000 – Why? • The transfer method of Bank class is not atomic: consists of many steps • Can be interrupted in the middle
  • 48. Synchronization • Problem scenario: – Thread 1 • Takes 50 from Account A • Reads current balance of Account B and stores value in variable tmp • Goes to sleep (simulate interruption, self interruption) – Thread 2 • Deposit some fund to Account B – Thread 1 • Update balance of Account B: tmp + 50 – Result: • Deposit by Thread 2 is lost! • The total amount can only be less than 100,000
  • 49. Synchronization • Note that even instructions are not atomic. – Consider the following accounts[to] += amount; – It is processed in three steps as follows: 1. Load current value of accounts[to] to a register 2. Add amount 3. Move the result back to accounts[to].
  • 50. Synchronization • Execution interruption accounts[0] is currently 100. Thread 1 perform accounts[0] += 50; Thread 2 performs accounts[0] += 50; The correct result should be: accounts[0] == 200. What is the result if the following happens? Actual result: accounts[0] == 150 The probability of such interruptions is low (but possible). This is why we faked interruption using sleep. Thread 1 Steps 1, 2 Step 3 Thread 2 Steps 1, 2, 3
  • 51. Synchronization • How to avoid the work of the transfer method being interrupted? – In java, the answer is to make the method synchronized. class Bank { … public synchronized void transfer(int from, int to,int amount) { while (accounts[from] < amount ) {…} accounts[from] -= amount; try { Thread.sleep(1); } catch(InterruptedException e) {} accounts[to] += amount; ntransacts++; if (ntransacts % 1000 == 0) test(); } } // SynchronizedBankTest0.java
  • 52. Synchronization • How does the mechanism work? – Object locks • When a thread calls a synchronized method of an object, the object is locked. • All other threads that try to call synchronized methods of the object are blocked. – The thread inside the object can of course call all synchronized methods – Threads that call unsynchronized methods of the object can proceed. • When the thread that locked the object finishes or terminates because of uncaught exception, it relinquishes the object lock • Periodically, the thread scheduler activates the threads waiting for the lock. They all become runnable. • When one of the blocked threads is scheduled to run, it checks to see if the object is locked. If not, it proceeds and locks the object.
  • 53. Synchronization • In the bank example, if a thread is executing b.transfer(…), it locks the Bank object b. • While b is locked, other threads trying to call b.transfer(…) are blocked. • b.transfer(…) is not interrupted.
  • 54. Synchronization • When the thread that locks b finishes, it gives up the object lock. The “door” is again open. • Periodically, the thread scheduler unblocks all threads waiting for the object lock • When such a thread is scheduled to run again, it checks whether b is still locked. If not, it proceeds and locks b. • Otherwise, it becomes blocked again.
  • 55. Synchronization • Note that SynchronizedBankTest0.java is much slower than UnsynchronizedBankTest.java – Other threads trying to get into an bank account cannot do so if it is locked by another thread, even that thread is sleeping inside! • Synchronization takes time. – Reason why not all methods are synchronized. – In particular, most methods of classes in Swing are not synchronized. • Swing is not thread-safe.
  • 56. Synchronization/wait and notify • What to do when the from account does not have sufficient fund? – Currently, transfer nonetheless – One possible solution public synchronized void transfer(int from, int to, int amount) { if (accounts[from] < amount) return ; – Obviously not good solutions.
  • 57. Synchronization/wait and notify • How about this? public void synchronized transfer(int from, int to, int amount) { while (accounts[from] < amount) { try { Thread.sleep(5); }catch(InterruptedException e) {} } • The idea is – The balance of the from account might increase after 5 milliseconds • But does not work: – A sleeping thread does not relinquishes its object locks – In the case, no other threads can get in the bank object and make transfers – Account balances will be the same when the thread wakes up.
  • 58. Synchronization/wait and notify • Solution: Call wait instead of sleep. public synchronized void transfer(int from, int to, int amount) { while (accounts[from] < amount) { try { wait(); } catch(InterruptedException e) {} } …}
  • 60. Synchronization/wait and notify • wait is a method of the Object class. It causes the calling method to wait (blocked) until notified (when another thread calls notify or notifyAll) • While waiting, a thread relinquishes its object locks. This gives other thread a chance to access the object. • notify or notifyAll are all methods of the Object class. – notify randomly selects a thread among those waiting for an object lock (inside the object) and unblocks it. – notifyAll unblocks all threads waiting for an object lock (inside the object). Preferred because it reduces the probability of deadlock (Exercise: Why is this?). • Note: wait, notify and notifyAll should only be called by a thread that is the owner of this object's monitor (within synchronized method).
  • 61. Synchronization/wait and notify • In our example, a thread calls notifyAll when it is done with a object. public synchronized void transfer(int from, int to, int amount) { while (accounts[from] < amount) { try { wait(); } catch(InterruptedException e) {} } … notifyAll(); …} SynchBankTest.java
  • 62. Synchronization/Deadlock Deadlock occurs when a number of threads waiting for each other Example: Account 1: $2,000 Account 2: $3,000 Thread 1: Transfer $3,000 from account 1 to account 2 Thread 2: Transfer $4,000 from account 2 to account 1 It is the responsibility of programmer to avoid deadlocks.
  • 63. Outline • Introduction: Why and what • Basics: creating and running threads • Issues – Thread states – Thread scheduling – Synchronization – Suspending and stopping threads
  • 64. Stopping and Suspending Threads The stop method is deprecated because it can corrupt objects. Consider a thread that is transferring money from one account to another. If the thread is stopped after withdrawal from the first account and before deposit to the second account, an error arises. (Other threads can continue since the stopped thread releases all locks.)
  • 65. How to stop a thread safely? Introduce variable stopRequested and check it in a safe place of the run method Public class MyThread extends Thread { public void run () { try { while ( !stopRequested && more work to do) { do more work} } catch (InterruptedException e) { if (stopRequested ) return; } } public void requestStop() { stopRequested = true; interrupt(); } private boolean stopRequested = false; } To terminate a thread t, call t.requestStop();
  • 66. Why and how does it work: If thread t is running and no more work to do, run method returns naturally. (Natural death). If t.requestStop() is called, 1. While t is running. The thread will exit the next time it checks the condition “!stopRequested”. (It will not stop in the middle of executing a synchronized method and hence does not lead to corrupted objects.) 2. While t is sleeping or blocked. The thread is interrupted, causing an InterruptedException. The exception handler will terminate the thread. To avoid corrupted objects, make sure that a thread doesn’t sleep while executing a synchronized method. You should never do this anyway. Waiting is no problem because it gives up object lock) Stopping and Suspending Threads
  • 67. Stopping and Suspending Threads The suspend and resume methods are deprecated because they can easily lead to deadlocks. (Suspended threads do not release object locks.) Suppose you suspend a thread t1, and t1 has locked an object x. Further suppose t2 is responsible to resume t1 but it needs to access a synchronized method of x first. Then, deadlock results. The resume method is deprecated because suspend is.
  • 68. How to suspend a thread safely? Use the wait and notifyAll methods Suspend by calling wait and resume using notifyAll 1. Write a class so that we can use its objects for locks public class suspenderRequestor { public synchronized void set (boolean b) { suspendRequested = b; notifyAll();} public synchronized void waiteForResume() throws InterruptedException { while ( suspendRequested) wait (); } private boolean suspendRequested }
  • 69. 2. Structure your thread class as follows public class MyThread extends Thread { public void requestSuspend() { suspender.set( true ); } public synchronized void requestResume() { suspender.set(false);} public void run () { while ( more work to do) { suspender.waitForResume();// call this once in a while do more work; } } private SuspendRequestor suspender = new SuspendRequestor(); } To suspend and resume a thread t, call t.requestSuspend(); t.requestResume();
  • 70. Stopping and Suspending Threads Why and how does this work? If t.requestSuspend() is called, suspender.suspendRequest becomes true. The next time t calls suspender.waitForResume(), t waits inside object suspender. It will resume only when another thread calls t.requestResume(), which calls suspender.set(true), which in turn notifies t. While t is waiting, it releases all object locks. This is different from suspend.
  • 71. Outline • Introduction: Why and what • Basics: creating and running threads • Issues – Thread states – Thread scheduling – Synchronization – Suspending and stopping threads
  • 72. Animation • Animation: a separate thread to sequentially display a sequence of images, each of which is called a frame. • Managing images 1. You can put each frame in a separate file, or 2. Put all frames on one file. (See right). We have studied case1 in RunnableTest.java.
  • 73. Animation • Show one frame of image public class Animation extends JApplet { public void loadImage(URL url).. { // size applet to the size of one frame resize(imageWidth, imageHeight / imageCount); } public void paint(Graphics g) { if (image == null) return; // put this point at the upper-left // corner of applet g.drawImage(image, 0, -(imageHeight/imageCount) * current, null); } … Applet
  • 74. Animation • Lunching new thread for showing frames public class Animation extends JApplet { public void start() { runner = new Thread() { public void run() { try { while (!Thread.interrupted()) { repaint(); current = (current + 1) % imageCount; Thread.sleep(200); } } catch(InterruptedException e) {} }}; runner.start(); showStatus("Click to stop"); }
  • 75. Outline • Introduction: Why and what • Basics: creating and running threads • Issues – Thread states – Thread scheduling – Synchronization – Suspending and stopping threads
  • 76. Threads and Swing Threads in a Swing program: Main thread: started by main method and usually exits after displaying frame window. Event dispatch thread: started when the first window is shown and stays alive until terminated by user. Event dispatch thread runs codes for handling events such as calls to actionPerformed or paintComponent.
  • 77. Threads and Swing From the event dispatch thread, one wants to fire up threads for Time-consuming actions Actions that can be blocked on I/O Sleeping Otherwise, GUI might seem dead or frozen.
  • 78. Threads and Swing Caution: Swing is not thread safe! Most methods in Swing classes are not synchronized. If one tamper with UI components from different threads, UI might be corrupted. Single thread rule for Swing programming Modify UI components only in the event dispatch thread Other threads should send actions that modify UI components to the event dispatch thread using the invokeLater or invokeAndWait methods of the EventQueue class (see textbook for details.) //swingThreadTest.java
  • 79. Summary of classes and methods • public class Thread extends Object implements Runnable – Thread() , Thread(Runnable target) – Constants: MAX_PRIORITY NORMAL_PRIORITY, MIN_PRIORITY – static: sleep, yield, interrupted – start, run, setPriority, setPriority, interrupt – isAlive, isInterrupted • public interface Runnable – run • public class Object – wait, notify, notifyAll • public class InterruptedException extends Exception