文档

Java™ 教程-Java Tutorials 中文版
Trail: Creating a GUI With JFC/Swing
主页>使用 JFC/Swing 创建 GUI

Answers: Concurrency in Swing

问题

问题1:For each of the following tasks, specify which thread it should be executed in and why.
答案1:

问题2:One thread is not the preferred thread for any of the tasks mentioned in the previous question. Name this thread and explain why its applications are so limited.
答案2:The initial threads launch the first GUI task on the event dispatch thread. After that, a Swing program is primarily driven by GUI events, which trigger tasks on the event dispatch thread and the worker thread. Usually, the initial threads are left with nothing to do.

问题3:SwingWorker has two type parameters. Explain how these type parameters are used, and why it often doesn't matter what they are.
答案3:The type parameters specify the type of the final result (also the return type of the doInBackground method) and the type of interim results (also the argument types for publish and process). Many background tasks do not provide final or interim results.

练习

问题1:Modify the Flipper example so that it pauses 5 seconds between "coin flips." If the user clicks the "Cancel", the coin-flipping loop terminates immediately.
答案1:See the source code for Flipper2. The modified program adds a delay in the central doInBackground loop:

protected Object doInBackground() {
    long heads = 0;
    long total = 0;
    Random random = new Random();
    while (!isCancelled()) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            //Cancelled!
            return null;
        }
        total++;
        if (random.nextBoolean()) {
            heads++;
        }
        publish(new FlipPair(heads, total));
    }
    return null;
}

The try ... catch causes doInBackground to return if an interrupt is received while the thread is sleeping. Invoking cancel with an argument of true ensures that an interrupt is sent when the task is cancelled.


Previous page: Questions and Exercises: Concurrency in Swing