OnJava8-Examples/gui/InterruptableLongRunningTask.java

50 lines
1.3 KiB
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: gui/InterruptableLongRunningTask.java
// Long-running tasks in threads.
import javax.swing.*;
import java.awt.*;
import java.util.concurrent.*;
import static net.mindview.util.SwingConsole.*;
class Task implements Runnable {
private static int counter = 0;
private final int id = counter++;
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public void run() {
System.out.println(this + " started");
try {
TimeUnit.SECONDS.sleep(3);
} catch(InterruptedException e) {
System.out.println(this + " interrupted");
return;
}
System.out.println(this + " completed");
}
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public String toString() { return "Task " + id; }
public long id() { return id; }
};
public class InterruptableLongRunningTask extends JFrame {
private JButton
b1 = new JButton("Start Long Running Task"),
b2 = new JButton("End Long Running Task");
ExecutorService executor =
Executors.newSingleThreadExecutor();
public InterruptableLongRunningTask() {
2015-05-06 12:09:38 -07:00
b1.addActionListener(e -> {
2015-05-05 14:05:39 -07:00
Task task = new Task();
executor.execute(task);
System.out.println(task + " added to the queue");
2015-04-20 15:36:01 -07:00
});
2015-05-06 12:09:38 -07:00
b2.addActionListener(e -> {
2015-05-05 14:05:39 -07:00
executor.shutdownNow(); // Heavy-handed
2015-04-20 15:36:01 -07:00
});
setLayout(new FlowLayout());
add(b1);
add(b2);
}
public static void main(String[] args) {
run(new InterruptableLongRunningTask(), 200, 150);
}
} ///:~