0

我想让 3 个线程同时执行一项任务,并且我想要一个线程在一段时间内执行计划任务(每 10 秒运行一次)。但是我希望当 3 个线程完成时只运行一次计划任务,然后我希望这个线程终止。实现这些线程的最佳方法是什么?ExecutorService 接口是否适合这个。

4

2 回答 2

3

这是我刚刚写的一个例子:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class Example {

    public static void main(String[] args) throws InterruptedException {
        ScheduledFuture future = Executors.newScheduledThreadPool(1).scheduleAtFixedRate(new MyScheduledTask(), 0, 10, TimeUnit.SECONDS);
        ExecutorService executor = Executors.newFixedThreadPool(3); // pool composed of 3 threads
        for (int i = 0; i < 3; i++) {
            // for the example assuming that the 3 threads execute the same task.
            executor.execute(new AnyTask()); 
        }
        // This will make the executor accept no new threads
        // and finish all existing threads in the queue
        executor.shutdown();
        // expect current thread to wait for the ending of the 3 threads
        executor.awaitTermination(Long.MAX_VALUE, TimeUnit.TimeUnit.NANOSECONDS); 
        future.cancel(false); // to exit properly the scheduled task
        // reprocessing the scheduled task only one time as expected
        new Thread(new ScheduledTask()).start(); 

    }


}

class MyScheduledTask implements Runnable {
    @Override
    public void run() {
        //Process scheduled task here
    }
}

class AnyTask implements Runnable {
    @Override
    public void run() {
        //Process job of threads here
    }
}
于 2012-10-24T01:41:02.183 回答
1

这是一个周期性任务计划程序的示例,它一个接一个地执行任务。任务调度程序接受一组任务,并在指定的时间间隔后在单独的线程中终止每个任务。20 秒后,主线程关闭调度程序并停止所有等待任务。

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class Example {

    class ScheduledRepeatingTask implements Runnable {
        final ScheduledExecutorService scheduler = Executors
                .newScheduledThreadPool(1);

        List<Runnable> taskCollection;
        Iterator<Runnable> taskIterator;

        Runnable getCancelRunnable(final ScheduledFuture<?> future) {

            Runnable cancelFuture = new Runnable() {
                public void run() {
                    future.cancel(true);
                }
            };
            return cancelFuture;
        }

        public ScheduledRepeatingTask(Runnable[] tasks) {
            super();
            taskCollection = Arrays.asList(tasks);
            taskIterator = taskCollection.iterator();
        }

        public void shutdownScheduler() throws InterruptedException {
            scheduler.shutdown();
            boolean execTerminated = scheduler.awaitTermination(5,
                    TimeUnit.SECONDS);

            if (!execTerminated) {
                scheduler.shutdownNow();
            }
        }

        public boolean isShutdown(){            
            return scheduler.isShutdown();
        }

        public void scheduleRepeatingTask(ScheduledFuture<?> future,
                ScheduledFuture<?> futureCancel) {

            try {
                futureCancel.get();
                future.get();

            } catch (CancellationException e) {
                System.out.println("cancelled.");
            } catch (ExecutionException e) {
                Throwable exp = e.getCause();
                if (exp instanceof RuntimeException) {
                    System.out.println("failed.");
                    RuntimeException rt = (RuntimeException) exp;
                    throw rt;
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                if (!scheduler.isShutdown() && taskIterator.hasNext()) {
                    future = scheduler.scheduleAtFixedRate(taskIterator.next(),
                            2, 2, TimeUnit.SECONDS);
                    futureCancel = scheduler.schedule(
                            getCancelRunnable(future), 5, TimeUnit.SECONDS);
                    scheduleRepeatingTask(future, futureCancel);

                }
            }
        }

        @Override
        public void run() {
            if (!scheduler.isShutdown() && taskIterator.hasNext()) {
                ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(
                        taskIterator.next(), 2, 2, TimeUnit.SECONDS);
                ScheduledFuture<?> futureCancel = scheduler.schedule(
                        getCancelRunnable(future), 5, TimeUnit.SECONDS);
                scheduleRepeatingTask(future, futureCancel);
            }
        }

    }

    public static void main(String[] args) throws InterruptedException {
        Example example = new Example();
        ExecutorService executor = Executors.newCachedThreadPool(); 

        Runnable[] tasks = { new Task1(), new Task2(), new Task1() };

        ScheduledRepeatingTask scheduledRepeatingTask = example.new ScheduledRepeatingTask(tasks);

        executor.execute(scheduledRepeatingTask);

        Thread.sleep(20000);

        scheduledRepeatingTask.shutdownScheduler();

        executor.shutdown();

    }

}

class Task1 implements Runnable {
    @Override
    public void run() {
        System.out.println("Task 1");
    }
}

class Task2 implements Runnable {
    @Override
    public void run() {
        System.out.println("Task 2");
    }
}
于 2012-10-24T08:53:03.500 回答