Java Tutorial/Thread/ScheduledThreadPoolExecutor
Animation with ScheduledThreadPoolExecutor
<source lang="java">
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.geom.Ellipse2D; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javax.swing.JComponent; import javax.swing.JFrame; public class BallRoom {
public static void main(String[] a){ JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(200, 300); PaintSurface canvas = new PaintSurface(); ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(3); executor.scheduleAtFixedRate(canvas, 0L, 100L, TimeUnit.MILLISECONDS); f.getContentPane().add(canvas); f.setVisible(true); }
} class PaintSurface extends JComponent implements Runnable{
int i = 0; public void run() { repaint(); } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Shape ball = new Ellipse2D.Float(i++, i++, 5, 5); g2.setColor(Color.RED); g2.fill(ball); }
}</source>
JDK1.5 provides a mechanism to create a pool a scheduled task
<source lang="java">
import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class Main{
public static void main(String args[]) { ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(5); stpe.scheduleAtFixedRate(new Job1(), 0, 5, TimeUnit.SECONDS); stpe.scheduleAtFixedRate(new Job2(), 1, 2, TimeUnit.SECONDS); }
} class Job1 implements Runnable {
public void run() { System.out.println("Job 1"); }
} class Job2 implements Runnable {
public void run() { for(int i=0;i<99;i++){ System.out.println(i); } }
}</source>
Return a value from a thread.
<source lang="java">
import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Main {
public static void main(String args[]) throws Exception{ ExecutorService es = Executors.newFixedThreadPool(3); Future<Double> f = es.submit(new Task1()); Future<Integer> f2 = es.submit(new Task2()); System.out.println(f.get()); System.out.println(f2.get()); es.shutdown(); }
} class Task1 implements Callable<Double> {
Task1() { } public Double call() { return 0.0; }
} class Task2 implements Callable<Integer> {
Task2() { } public Integer call() { return 1; }
}</source>