Multithreading / Concurrency
Multithreading / Concurrency
Chapter 29
Multithreading / Concurrency
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
2
Thread
• Thread: single sequential flow of control within a
program
• Single-threaded program can handle one task at
any time.
• Multitasking allows single processor to run
several concurrent threads.
• Most modern operating systems support
multitasking.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
3
Advantages of Multithreading
• Reactive systems – constantly monitoring
• More responsive to user input – GUI application
can interrupt a time-consuming task
• Server can handle multiple clients
simultaneously
• Can take advantage of parallel processing
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
4
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
5
Threads Concept
Multiple Thread 1
threads on
Thread 2
multiple
Thread 3
CPUs
Multiple Thread 1
threads
Thread 2
sharing a
Thread 3
single CPU
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
6
Threads in Java
Creating threads in Java:
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
7
Threads in Java
Creating threads in Java:
• Extend java.lang.Thread class
▫ run() method must be overridden (similar to main
method of sequential program)
▫ run() is called when execution of the thread begins
▫ A thread terminates when run() returns
▫ start() method invokes run()
▫ Calling run() does not create a new thread
• Implement java.lang.Runnable interface
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
8
Threads in Java
Creating threads in Java:
• Extend java.lang.Thread class
• Implement java.lang.Runnable interface
▫ If already inheriting another class (i.e., JApplet)
▫ Single method: public void run()
▫ Thread class implements Runnable.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
9
Thread States
http://www.deitel.com/articles/java_tutorials/20051126/JavaMultithrea
ding_Tutorial_Part2.html
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
10
Thread termination
A thread becomes Not Runnable when one of
these events occurs:
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
11
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
12
Example:
Using the Runnable Interface to Create
and Launch Threads
TaskThreadDemo Run
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
13
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
14
The Static yield() Method
You can use the yield() method to temporarily release
time for other threads. For example, suppose you
modify the code in Lines 53-57 in
TaskThreadDemo.java as follows:
public void run() {
for (int i = 1; i <= lastNum; i++) {
System.out.print(" " + i);
Thread.yield();
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
15
The Static sleep(milliseconds) Method
The sleep(long mills) method puts the thread to sleep for the
specified time in milliseconds. For example, suppose you
modify the code in Lines 53-57 in TaskThreadDemo.java as
follows:
public void run() {
for (int i = 1; i <= lastNum; i++) {
System.out.print(" " + i);
try {
if (i >= 50) Thread.sleep(1);
}
catch (InterruptedException ex) {
}
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
16
The join() Method
You can use the join() method to force one thread to wait for
another thread to finish. For example, suppose you modify the
code in Lines 53-57 in TaskThreadDemo.java as follows:
yield(), or Running
time out run() returns
Thread created start()
New Ready run() join() Finished
interrupt() sleep()
Target wait()
finished
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
18
Thread methods
isAlive()
• method used to find out the state of a thread.
• returns true: thread is in the Ready, Blocked, or
Running state
• returns false: thread is new and has not started or if it is
finished.
interrupt()
f a thread is currently in the Ready or Running state, its
interrupted flag is set; if a thread is currently blocked, it
is awakened and enters the Ready state, and an
java.io.InterruptedException is thrown.
The isInterrupt() method tests whether the thread is
interrupted.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
19
The deprecated stop(), suspend(), and
resume() Methods
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
20
Thread Priority
• Each thread is assigned a default priority of
Thread.NORM_PRIORITY (constant of 5). You
can reset the priority using setPriority(int
priority).
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
21
Thread Scheduling
• An operating system’s thread scheduler
determines which thread runs next.
• Most operating systems use timeslicing for
threads of equal priority.
• Preemptive scheduling: when a thread of higher
priority enters the running state, it preempts the
current thread.
• Starvation: Higher-priority threads can
postpone (possible forever) the execution of
lower-priority threads.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
22
FlashingText Run
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
23
Thread Pools
• Starting a new thread for each task could limit throughput and cause
poor performance.
• A thread pool is ideal to manage the number of tasks executing
concurrently.
• Executor interface for executing Runnable objects in a thread pool
•ExecutorService is a subinterface of Executor.
«interface»
java.util.concurrent.Executor
+execute(Runnable object): void Executes the runnable task.
\
«interface»
java.util.concurrent.ExecutorService
+shutdown(): void Shuts down the executor, but allows the tasks in the executor to
complete. Once shutdown, it cannot accept new tasks.
+shutdownNow(): List<Runnable> Shuts down the executor immediately even though there are
unfinished threads in the pool. Returns a list of unfinished
tasks.
+isShutdown(): boolean Returns true if the executor has been shutdown.
+isTerminated(): boolean Returns true if all tasks in the pool are terminated.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
24
Creating Executors
To create an Executor object, use the static methods in the Executors
class.
java.util.concurrent.Executors
+newFixedThreadPool(numberOfThreads: Creates a thread pool with a fixed number of threads executing
int): ExecutorService concurrently. A thread may be reused to execute another task
after its current task is finished.
+newCachedThreadPool(): Creates a thread pool that creates new threads as needed, but
ExecutorService will reuse previously constructed threads when they are
available.
ExecutorDemo Run
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
25
Thread Synchronization
1 0 newBalance = bank.getBalance() + 1;
2 0 newBalance = bank.getBalance() + 1;
3 1 bank.setBalance(newBalance);
4 1 bank.setBalance(newBalance);
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
26
AccountWithoutSync
Run
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
27
Race Condition
What, then, caused the error in the example? Here is a possible scenario:
1 0 newBalance = balance + 1;
2 0 newBalance = balance + 1;
3 1 balance = newBalance;
4 1 balance = newBalance;
);
• Effect: Task 1 did nothing (in Step 4 Task 2 overrides the result)
• Problem: Task 1 and Task 2 are accessing a common resource in a
way that causes conflict.
• Known as a race condition in multithreaded programs.
•A thread-safe class does not cause a race condition in the presence
of multiple threads.
•The Account class is not thread-safe.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
28
synchronized
•Problem: race conditions
•Solution: give exclusive access to one thread at a time to code
that manipulates a shared object.
•Synchronization keeps other threads waiting until the object is
available.
•The synchronized keyword synchronizes the method so that
only one thread can access the method at a time.
•The critical region in the Listing 29.7 is the entire deposit
method.
•One way to correct the problem in Listing 29.7: make Account
thread-safe by adding the synchronized keyword in deposit:
public synchronized void deposit(double amount)
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
29
Synchronizing Instance Methods and Static
Methods
•A synchronized method acquires a lock before it
executes.
•Instance method: the lock is on the object for which it
was invoked.
•Static method: the lock is on the class.
•If one thread invokes a synchronized instance method
(respectively, static method) on an object, the lock of
that object (respectively, class) is acquired, then the
method is executed, and finally the lock is released.
•Another thread invoking the same method of that
object (respectively, class) is blocked until the lock is
released.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
30
Synchronizing Instance Methods and Static
Methods
With the deposit method synchronized, the preceding scenario
cannot happen. If Task 2 starts to enter the method, and Task 1
is already in the method, Task 2 is blocked until Task 1 finishes
the method.
Task 1 Task 2
Acquire a-char
locktoken
on the object account -char token
+getToken +getToken
-char token +setToken +setToken
+paintComponet +paintComponet
Execute
+getToken the deposit method
+mouseClicked +mouseClicked
+setToken
+paintComponet Wait to acquire the lock
-char token
+mouseClicked
-char token
+getToken Release the lock
+setToken
+getToken
+paintComponet
-char token Acqurie a lock on the object account
+setToken
+mouseClicked
+paintComponet
+getToken -char token
+mouseClicked
+setToken
+paintComponet Execute the deposit method
+getToken
+mouseClicked +setToken
+paintComponet
-char token
+mouseClicked
+getToken Release the lock
+setToken
+paintComponet
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
31
Synchronizing Statements
•Invoking a synchronized instance method of an object acquires
a lock on the object.
•Invoking a synchronized static method of a class acquires a
lock on the class.
•A synchronized block can be used to acquire a lock on any
object, not just this object, when executing a block of code.
synchronized (expr) {
statements;
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
32
Synchronizing Statements vs. Methods
Any synchronized instance method can be converted into a
synchronized statement. Suppose that the following is a
synchronized instance method:
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
33
Synchronization Using Locks
•A synchronized instance method implicitly acquires a lock on
the instance before it executes the method.
•You can use locks explicitly to obtain more control for
coordinating threads.
•A lock is an instance of the Lock interface, which declares the
methods for acquiring and releasing locks.
•newCondition() method creates Condition objects, which can
be used for thread communication.
«interface»
java.util.concurrent.locks.Lock
+lock(): void Acquires the lock.
+unlock(): void Releases the lock.
+newCondition(): Condition Returns a new Condition instance that is bound to this
Lock instance.
java.util.concurrent.locks.ReentrantLock
+ReentrantLock() Same as ReentrantLock(false).
+ReentrantLock(fair: boolean) Creates a lock with the given fairness policy. When the
fairness is true, the longest-waiting thread will get the
lock. Otherwise, there is no particular access order.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
34
Fairness Policy
•ReentrantLock:concrete implementation of Lock for
creating mutually exclusive locks.
•Create a lock with the specified fairness policy.
•True fairness policies guarantee the longest-wait
thread to obtain the lock first.
•False fairness policies grant a lock to a waiting thread
without any access order.
•Programs using fair locks accessed by many threads
may have poor overall performance than those using
the default setting, but have smaller variances in times
to obtain locks and guarantee lack of starvation.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
35
Example: Using Locks
This example revises AccountWithoutSync.java in
Listing 29.7 to synchronize the account modification
using explicit locks.
AccountWithSyncUsingLock
Run
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
36
Cooperation Among Threads
•Conditions can be used for communication among threads.
•A thread can specify what to do under a certain condition.
•newCondition() method of Lock object.
•Condition methods:
•await() current thread waits until the condition is signaled
•signal() wakes up a waiting thread
•signalAll() wakes all waiting threads
«interface»
java.util.concurrent.Condition
+await(): void Causes the current thread to wait until the condition is signaled.
+signal(): void Wakes up one waiting thread.
+signalAll(): Condition Wakes up all waiting threads.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
37
Cooperation Among Threads
•Lock with a condition to synchronize operations: newDeposit
•If the balance is less than the amount to be withdrawn, the
withdraw task will wait for the newDeposit condition.
•When the deposit task adds money to the account, the task
signals the waiting withdraw task to try again.
ThreadCooperation
Run
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
39
Java’s Built-in Monitors (Optional)
•Locks and conditions are new in Java 5.
•Prior to Java 5, thread communications were programmed
using object’s built-in monitors.
•Locks and conditions are more powerful and flexible than
the built-in monitor.
•A monitor is an object with mutual exclusion and
synchronization capabilities.
•Only one thread can execute a method at a time in the
monitor.
•A thread enters the monitor by acquiring a lock
(synchronized keyword on method / block) on the monitor
and exits by releasing the lock.
•A thread can wait in a monitor if the condition is not right
for it to continue executing in the monitor.
•Any object can be a monitor. An object becomes a monitor
once a thread locks it.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
40
wait(), notify(), and notifyAll()
Use the wait(), notify(), and notifyAll() methods to facilitate
communication among threads.
The wait() method lets the thread wait until some condition
occurs. When it occurs, you can use the notify() or notifyAll()
methods to notify the waiting threads to resume normal
execution. The notifyAll() method wakes up all waiting threads,
while notify() picks up only one thread from a waiting queue.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
41
Example: Using Monitor
Task 1 Task 2
synchronized (anObject) {
try { synchronized (anObject) {
// Wait for the condition to become true // When condition becomes true
while (!condition) resume anObject.notify(); or anObject.notifyAll();
anObject.wait(); ...
}
// Do something when condition is true
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
}
+getToken +getToken
Delete an int to the buffer
Add an int to the buffer
+setToken +setToken
+paintComponet +paintComponet
-char token
-char token
+mouseClicked +mouseClicked
+getToken +getToken
notEmpty.signal(); notFull.signal();
+setToken +setToken
+paintComponet +paintComponet
-char token -char token
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
43
Case Study: Producer/Consumer (Optional)
Listing 29.10 presents the complete program. The program
contains the Buffer class (lines 43-89) and two tasks for
repeatedly producing and consuming numbers to and from the
buffer (lines 15-41). The write(int) method (line 58) adds an
integer to the buffer. The read() method (line 75) deletes and
returns an integer from the buffer.
ConsumerProducer Run
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
44
Blocking Queues (Optional)
§22.8 introduced queues and priority queues. A
blocking queue causes a thread to block when you try
to add an element to a full queue or to remove an
element from an empty queue.
«interface»
java.util.Collection<E>
«interface»
java.util.Queue<E>
«interface»
java.util.concurrent.BlockingQueue<E>
+put(element: E): void Inserts an element to the tail of the queue.
Waits if the queue is full.
+take(): E Retrieves and removes the head of this
queue. Waits if the queue is empty.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
45
Concrete Blocking Queues
Three concrete blocking queues ArrayBlockingQueue,
LinkedBlockingQueue, and PriorityBlockingQueue are supported in JDK
1.5, as shown in Figure 29.22. All are in the java.util.concurrent package.
ArrayBlockingQueue implements a blocking queue using an array. You
have to specify a capacity or an optional fairness to construct an
ArrayBlockingQueue. LinkedBlockingQueue implements a blocking queue
using a linked list. You may create an unbounded or bounded
LinkedBlockingQueue. PriorityBlockingQueue is a priority queue. You may
create an unbounded or bounded priority queue.
«interface»
java.util.concurrent.BlockingQueue<E>
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
46
Producer/Consumer Using Blocking Queues
Listing 29.11 gives an example of using an ArrayBlockingQueue
to simplify the Consumer/Producer example in Listing 29.11.
ConsumerProducerUsingBlockingQueue Run
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
47
Semaphores (Optional)
Semaphores can be used to restrict the number of threads that
access a shared resource. Before accessing the resource, a
thread must acquire a permit from the semaphore. After
finishing with the resource, the thread must return the permit
back to the semaphore, as shown in Figure 29.29.
-char token
-char token
+getToken
Acquire a permit from a semaphore. semaphore.acquire();
+setToken
Wait if the permit is not available. +getToken
+paintComponet +setToken
+mouseClicked
-char token +paintComponet
+mouseClicked
+getToken
Access the resource Access the resource
+setToken
+paintComponet
-char token -char token
+mouseClicked
+getToken +getToken
Release the permit to the semaphore semaphore.release();
+setToken +setToken
+paintComponet +paintComponet
-char token -char token
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
48
Creating Semaphores
To create a semaphore, you have to specify the number of
permits with an optional fairness policy, as shown in
Figure 29.29. A task acquires a permit by invoking the
semaphore’s acquire() method and releases the permit by
invoking the semaphore’s release() method. Once a permit
is acquired, the total number of available permits in a
semaphore is reduced by 1. Once a permit is released, the
total number of available permits in a semaphore is
increased by 1.
java.util.concurrent.Semaphore
+Semaphore(numberOfPermits: int) Creates a semaphore with the specified number of permits. The
fairness policy is false.
+Semaphore(numberOfPermits: int, fair: Creates a semaphore with the specified number of permits and
boolean) the fairness policy.
+acquire(): void Acquires a permit from this semaphore. If no permit is
available, the thread is blocked until one is available.
+release(): void Releases a permit back to the semaphore.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
49
Deadlock
•Sometimes two or more threads need to acquire the locks on several
shared objects.
•This could cause deadlock, in which each thread has the lock on one of the
objects and is waiting for the lock on the other object.
•In the figure below, the two threads wait for each other to release the in
order to get a lock, and neither can continue to run.
1 synchronized (object1) {
2 synchronized (object2) {
3 // do something here
4 // do something here
5 synchronized (object2) {
6 synchronized (object1) {
// do something here // do something here
} }
} }
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
50
Preventing Deadlock
•Deadlock can be easily avoided by resource ordering.
•With this technique, assign an order on all the objects whose
locks must be acquired and ensure that the locks are acquired
in that order.
•How does this prevent deadlock in the previous example?
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
51
Synchronized Collections
•The classes in the Java Collections Framework are not thread-
safe.
•Their contents may be corrupted if they are accessed and
updated concurrently by multiple threads.
•You can protect the data in a collection by locking the
collection or using synchronized collections.
The Collections class provides six static methods for creating
synchronization wrappers.
java.util.Collections
+synchronizedCollection(c: Collection): Collection Returns a synchronized collection.
+synchronizedList(list: List): List Returns a synchronized list from the specified list.
+synchronizedMap(m: Map): Map Returns a synchronized map from the specified map.
+synchronizedSet(s: Set): Set Returns a synchronized set from the specified set.
+synchronizedSortedMap(s: SortedMap): SortedMap Returns a synchronized sorted map from the specified
sorted map.
+synchronizedSortedSet(s: SortedSet): SortedSet Returns a synchronized sorted set.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
52
Vector, Stack, and Hashtable
Invoking synchronizedCollection(Collection c) returns a new
Collection object, in which all the methods that access and update
the original collection c are synchronized. These methods are
implemented using the synchronized keyword. For example, the
add method is implemented like this:
public boolean add(E o) {
synchronized (this) { return c.add(o); }
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
53
Fail-Fast
The synchronization wrapper classes are thread-safe, but the iterator is fail-
fast. This means that if you are using an iterator to traverse a collection
while the underlying collection is being modified by another thread, then
the iterator will immediately fail by throwing
java.util.ConcurrentModificationException, which is a subclass of
RuntimeException. To avoid this error, you need to create a synchronized
collection object and acquire a lock on the object when traversing it. For
example, suppose you want to traverse a set, you have to write the code like
this:
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
54
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
55
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
56
Launch Application from Main Method
So far, you have launched your GUI application from
the main method by creating a frame and making it
visible. This works fine for most applications. In certain
situations, however, it could cause problems. To avoid
possible thread deadlock, you should launch GUI
creation from the event dispatcher thread as follows:
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
58
Run Audio on Separate Thread
When you run the preceding program, you will notice that the second
hand does not display at the first, second, and third seconds of the
minute. This is because sleep(1500) is invoked twice in the
announceTime() method, which takes three seconds to announce the
time at the beginning of each minute. Thus, the next action event is
delayed for three seconds during the first three seconds of each
minute. As a result of this delay, the time is not updated and the clock
was not repainted for these three seconds. To fix this problem, you
should announce the time on a separate thread. This can be
accomplished by modifying the announceTime method.
ClockWithAudioOnSeparateThread Run
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
59
SwingWorker
As discussed in §29.6, all Swing GUI events are processed in a
single event dispatch thread. If an event requires a long time to
process, the thread cannot attend to other tasks in the queue.
To solve this problem, you should run the time-consuming task
for processing the event in a separate thread. Java 6 introduced
SwingWorker. SwingWorker is an abstract class that
implements Runnable. You can define a task class that extends
SwingWorker, run the time-consuming task in the task, and
update the GUI using the results produced from the task.
Figure 29.28 defines SwingWorker.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
60
SwingWorker
«interface»
java.lang.Runnable
javax.swing.SwingWorker<T, V>
#doInBackground(): T Performs the task and return a result of type T.
#done(): void Executed on the Event Dispatch Thread after doInBackground is
finished.
+execute(): void Schedules this SwingWorker for execution on a worker thread.
+get(): T Waits if necessary for the computation to complete, and then retrieves
its result (i.e., the result returned doInBackground).
+isDone(): boolean Returns true if this task is completed.
+cancel(): boolean Attempts to cancel this task.
#publish(data V...): void Sends data for processing by the process method. This method is to be
used from inside doInBackground to deliver intermediate results
for processing on the event dispatch thread inside the process
method. Note that V… denotes variant arguments.
#process(data: java.util.List<V>): void Receives data from the publish method asynchronously on the Event
Dispatch Thread.
#setProgress(int progress): void Sets the progress bound property. The value should be from 0 to 100.
#getProgress(): void Returns the progress bound property.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
61
SwingWorker Demo
SwingWorkerDemo Run
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
62
TIP
Two things to remember when
writing Swing GUI programs,
• Time-consuming tasks should be
run in SwingWorker.
• Swing components should be
accessed from the event dispatch
thread only.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
63
Tutorial
• http://www.deitel.com/articles/java_tutorials/2
0051126/JavaMultithreading_Tutorial_Part1.ht
ml
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671