5 return;
6 }
7 }
8
SwingWorker 的 cancel 方法就是采用的第二种模式实现的,SwingWorker 的
cancel 方法调用其任务线程的 interrupt()方法,而 doInBackground 方法应该定期调
用 SwingWorker 的 isCanceled 方法判断当前任务是否被取消。isCanceled()最终调用
了 Thread.interrupted()方法检测当前线程是否接受到中断信号。
3.public static Thread currentThread()获得当前线程对象。
4.public boolean isInterrupted()该线程是否受到中断信号。
5.public static boolean interrupted(),检测当前线程是否接受到中断信号。它实
际上是调用了 Thread.currentThread().isInterrupted()实现的。
6.public final void join()该方法允许一个线程等待另一个线程的结束。比如 t 是一
个目前正在执行的线程,那么 t.join()将目前线程挂起直至线程 t 结束。
下面举例总结本节所说明的一些概念。SimpleThreads 由两个线程组成,第一个是主
线程,主线程使用一个 Runnable 对象 MessageLoop 创建一个新的线程,并等待该线
程结束。如果 MessageLoop 线程耗时太长,那么主线程将强制中断该线程。
MessageLoop 线程打印出一系列的消息,如果被中断,则打印消息并退出:
1 public class SimpleThreads {
2
3 //Display a message, preceded by the name of the current thread
4
5 static void threadMessage(String message) {
6
7 String threadName = Thread.currentThread().getName();
8
9 System.out.format("%s: %s%n", threadName, message);
10
11 }
12
13 private static class MessageLoop implements Runnable {
14
15 public void run() {
16
17 String importantInfo[] = {
18
19 "Mares eat oats",
20
21 "Does eat oats",
22
23 "Little lambs eat ivy",
24