Vous êtes sur la page 1sur 19

Java threads

Multitasking in Java

Threads in Java

The Java virtual machine allows


multithreading
Java threads are represented and
controlled by thread objects

But the threads themselves are not the thread


objects! They are a separate control flow.

The new control flow is created with the


threads start() method

The method returns immediately, but a new


thread start running

Creating and running


threads

There are two methods for creating


threads:
Sub-class Thread and override the run() method
Implement the Runnable interface and pass it as
constructor parameter to a new thread

The thread begins its execution when the


threads start() method is called

It is then initialized the thread and runs the


run() method of the thread or of the runnable
parameter

What actually happens


Client

Thread

Runnable

new(runnable)
start()

Init a new thread

run()
Runs in a new
control flow
Returns immediately

Thread is finished

doTheStuff()

A word on
synchronization

Each Java object has its own monitor


Resource sync. is done by this monitor

Synchronized block/method
synchronize {}
// sync. on this
synchronize(obj) {}// sync. on obj.

To enter the block/method, the thread


must obtain the objects lock
When the block/method is done, the lock
is released

A word on blocking

You can block the execution of a thread


using Objects wait() and notify() or
notifyAll() methods

The wait method returns only after notified

The thread must acquire the objects


lock to wait or to notify
When the thread waits, the lock is
released

It is re-acquired when notified

A threads life cycle


Alive
Blocked
Wait for
notify

Wait for
target

Sleeping

Running
wait()
notify() /
notifyAll()
join()

Not
interrupted

New
start()

interrupt()

Target finish
sleep()

Time out

Interrupted

Dead

interrupt()
run() returns

Swing and
threads
Multitasking in GUI
applications

Swings threads

Swings work is not done by the main


thread

It is done by a special thread

The main thread should only initialize the GUI


Called the event-dispatching thread

The event dispatcher is responsible to:


Execute events in a queue
Paint and update damaged widgets

Swings components are not thread-safe!

Only the event dispatcher should do these


things

Executing events

Creating new events:


The JVM handles OS interrupts
The interrupts are translated to events
The events are queued

The event-dispatchers loop:


De-queue the next event
Execute the event-handler (if any)
Repaint widgets (if necessary)

Executing events (2)


Events
queue

Events
dispatcher

Event
handler

Interruptenqueue(event)
Interruptenqueue(event)

dequeue()
event

handle(event)

dequeue()
event

handle(event)

Events handlers and


threads

Event handlers are executed by the event


dispatcher thread, one at a time
Executing event handlers freezes the GUI
No other events are executed
No repainting or updating

Therefore, event handlers should either:


Be very brief, and never with a blocking call
Use a different thread and release the dispatcher

Using another thread


Events
dispatcher

Event
handler

handle(event)

Worker
thread
start()

doTheStuff()

Thread is finished

Problems with
multithreaded GUI

Swing components are not thread-safe!

What happens if an interrupt occurs while


updating?

They should be accessed only by a single


thread
Preferably, the event-dispatching thread
So it is OK for event handlers to update the GUI,
but not for other threads
Exception: the repaint() and revalidate()
methods are thread-safe they are queued for
the event dispatcher

Queuing the event


dispatcher

The SwingUtilities class has methods for


queuing works to be executed by the eventdispatching thread (like events)

invokeLater(): returns immediately, work

executed later by the dispatcher


invokeAndWait(): waits until the dispatcher
executes the work and then returns (not
preferable)

Both methods takes a Runnable as parameter

The run() method is called by the event


dispatcher

Swing timers

A common task for a thread is to perform some


action repeating every given time
Swing has a special aux. class for that: Timer.
Takes a delay (in ms.) and an action listener as
constructor parameters
The action is performed each time after the delay

The timer actions are performed by the event


dispatcher, so they can update the GUI
There is also a general timer class at java.util

Performing queued
works

Swing
Utilities
inovkeLater()

Events
queue

Events
dispatcher Runnable

enqueue()

Later, when
there are
no events
dequeue()
runnable

run()

Update
things

Summary: Swing and


threads (1)

All the event handling and the refreshing in


Swing is done by the events dispatching
thread
Event handlers are executed from a queue
To avoid freezing the GUI, event handlers
must:
Be very brief
Not contain any blocking call (network, I/O)

To perform long or blocking work in event


handlers, always use a separate thread

Summary: Swing and


threads (2)

Swing components are not thread-safe

Only exceptions: refresh and revalidate methods

Only the event-dispatcher may update them


Event handlers may do updates
But only if they are executed by the event
dispatcher

To update the GUI by other threads, works are


queued in the events queue by special methods
Swings Timer also works with the events
queue

Vous aimerez peut-être aussi