几个任务洞察一个服务

时间:2015-03-09 20:56:42

标签: javafx javafx-2 javafx-8

我感兴趣的是有没有可以运行7个任务洞察一个服务?

private final DataService service = new DataService();

    class DataService extends ScheduledService<Void>
    {
        @Override
        protected Task<Void> createTask()
        {
            return new Task<Void>()
            {
                @Override
                protected Void call() throws Exception
                {

                    // Several tasks


                    return null;
                }
            };
        }
    }

在我的情况下,我需要并行运行任务。

1 个答案:

答案 0 :(得分:1)

class DataService extends ScheduledService<Void>
{

    private int numTasks ;

    public DataService(int numTasks) {
        setExecutor(Executors.newCachedThreadPool(r -> {
            Thread t = new Thread(r);
            t.setDaemon(true);
            return t ;
        }));
        this.numTasks = numTasks ;
    }

    @Override
    protected Task<Void> createTask()
    {
        return new Task<Void>()
        {
            @Override
            protected Void call() throws Exception
            {

                // Several tasks
                for (int i = 0; i < numTasks ; i++) {
                    final int taskNumber = i ;
                    Runnable task = () -> {
                        // code to execute task taskNumber...
                    };
                    getExecutor().execute(task);
                }
                return null;
            }
        };
    }
}

请注意,call方法将立即返回(即在各个任务完成之前),此时服务将进入“成功”状态。如果您希望call()方法等待各个任务完成,您可以执行以下操作:

class DataService extends ScheduledService<Void>
{
    private int numTasks ;

    private final ExecutorService exec = Executors.newCachedThreadPool(r -> {
            Thread t = new Thread(r);
            t.setDaemon(true);
            return t ;
        });

    public DataService(int numTasks) {
        setExecutor(exec);
        this.numTasks = numTasks ;
    }

    @Override
    protected Task<Void> createTask()
    {
        return new Task<Void>()
        {
            @Override
            protected Void call() throws Exception
            {

                // Several tasks
                List<Callable<Void>> tasks = new ArrayList<>();
                for (int i = 0; i < numTasks; i++) {
                    final int taskNumber = i ;
                    Callable<Void> task = () -> {
                        // code to execute task taskNumber...
                        return null ;
                    };
                    tasks.add(task);
                }

                exec.invokeAll(tasks);

                return null;
            }
        };
    }
}