您可能需要考虑使用 java.util.concurrent 包。您需要将工作步骤包装为 Callables(或 Runnables)。
public class InterruptibleTest {
public static void main(String[] args) { try {
final ExecutorService queue = Executors.newFixedThreadPool(1);
queue.submit(new Callable<Void>() { @Override public Void call() { busyWait(1000); return null; } });
queue.submit(new Callable<Void>() { @Override public Void call() { busyWait(1000); return null; } });
queue.submit(new Callable<Void>() { @Override public Void call() { busyWait(1000); return null; } });
final AtomicBoolean cancelled = new AtomicBoolean();
new Thread() { @Override public void run() {
try { Thread.sleep(1500); } catch (InterruptedException ex) { }
queue.shutdownNow();
cancelled.set(true);
}
}.run();
if (cancelled.get()) { rollback(); }
queue.shutdown();
System.out.println("Finished");
} catch (Exception ex) { ex.printStackTrace(System.err); } }
public synchronized static void busyWait(int millis) {
System.out.println("Start");
long until = System.currentTimeMillis() + millis;
while (System.currentTimeMillis() < until) { }
System.out.println("Stopped");
}
public synchronized static void rollback() {
System.out.println("Rollback!");
}
}
请注意,shutdownNow() 可能会在当前执行的工作线程上调用 interrupt()。您可能还需要同步您的 rollback(),因为 shutdownNow() 在不可中断代码完成执行之前返回。