OnJava8-Examples/gui/InterruptableLongRunningCallable.java

53 lines
1.5 KiB
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: gui/InterruptableLongRunningCallable.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
2015-04-20 15:36:01 -07:00
// Using Callables for long-running tasks.
import javax.swing.*;
import java.awt.*;
import java.util.concurrent.*;
import net.mindview.util.*;
import static net.mindview.util.SwingConsole.*;
class CallableTask extends Task
implements Callable<String> {
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public String call() {
run();
return "Return value of " + this;
}
}
public class
InterruptableLongRunningCallable extends JFrame {
private JButton
b1 = new JButton("Start Long Running Task"),
b2 = new JButton("End Long Running Task"),
b3 = new JButton("Get results");
private TaskManager<String,CallableTask> manager =
2015-05-05 11:20:13 -07:00
new TaskManager<>();
2015-04-20 15:36:01 -07:00
public InterruptableLongRunningCallable() {
2015-05-06 12:09:38 -07:00
b1.addActionListener(e -> {
2015-05-05 14:05:39 -07:00
CallableTask task = new CallableTask();
manager.add(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
for(String result : manager.purge())
System.out.println(result);
2015-04-20 15:36:01 -07:00
});
2015-05-06 12:09:38 -07:00
b3.addActionListener(e -> {
2015-05-05 14:05:39 -07:00
// Sample call to a Task method:
for(TaskItem<String,CallableTask> tt : manager)
tt.task.id(); // No cast required
for(String result : manager.getResults())
System.out.println(result);
2015-04-20 15:36:01 -07:00
});
setLayout(new FlowLayout());
add(b1);
add(b2);
add(b3);
}
public static void main(String[] args) {
run(new InterruptableLongRunningCallable(), 200, 150);
}
} ///:~