Objects that implement this interface are created with the
EventQueue#createSecondaryLoop method. The interface
provides two methods, enter and exit,
which can be used to start and stop the event loop.
When the enter method is called, the current
thread is blocked until the loop is terminated by the
exit method. Also, a new event loop is started
on the event dispatch thread, which may or may not be
the current thread. The loop can be terminated on any
thread by calling its exit method. After the
loop is terminated, the SecondaryLoop object can
be reused to run a new nested event loop.
A typical use case of applying this interface is AWT and Swing modal dialogs. When a modal dialog is shown on the event dispatch thread, it enters a new secondary loop. Later, when the dialog is hidden or disposed, it exits the loop, and the thread continues its execution.
The following example illustrates a simple use case of secondary loops:
SecondaryLoop loop;
JButton jButton = new JButton("Button");
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Toolkit tk = Toolkit.getDefaultToolkit();
EventQueue eq = tk.getSystemEventQueue();
loop = eq.createSecondaryLoop();
// Spawn a new thread to do the work
Thread worker = new WorkerThread();
worker.start();
// Enter the loop to block the current event
// handler, but leave UI responsive
if (!loop.enter()) {
// Report an error
}
}
});
class WorkerThread extends Thread {
@Override
public void run() {
// Perform calculations
doSomethingUseful();
// Exit the loop
loop.exit();
}
}
Dialog#show, EventQueue#createSecondaryLoop, Toolkit#getSystemEventQueue
| Modifier and Type | Method and Description |
|---|---|
| public boolean | Returns: true after termination of the secondary loop,
if the secondary loop was started by this call,
false otherwiseBlocks the execution of the current thread and enters a new secondary event loop on the event dispatch thread. |
| public boolean |
| enter | back to summary |
|---|---|
| public boolean enter() Blocks the execution of the current thread and enters a new secondary event loop on the event dispatch thread.
This method can be called by any thread including the event
dispatch thread. This thread will be blocked until the
This method can only start one new event loop at a time per
object. If a secondary event loop has already been started
by this object and is currently still running, this method
returns
| |
| exit | back to summary |
|---|---|
| public boolean exit() Unblocks the execution of the thread blocked by the
This method resumes the thread that called the Note that if any other secondary loop is started while this loop is running, the blocked thread will not resume execution until the nested loop is terminated.
If this secondary loop has not been started with the
| |