在执行程序服务延迟后安排任务

时间:2016-11-24 09:42:45

标签: java scheduledexecutorservice

我希望在延迟3秒后执行任务,我的一项任务需要2秒才能完成。

我得到的输出显示间隔为5秒

注意:Student类实现Callable接口 我有以下查询

  1. 为什么会有5秒的延迟。如何延迟3秒 秒为什么线程1在第二次执行时显示,应该是 线程二
  2. 我得到的输出是

    The time is : Sat Nov 26 15:08:02 IST 2016
    
    Doing a task during : prerna - Time - Sat Nov 26 15:08:06 IST 2016
    pool-1-thread-1 Helloprerna
    Doing a task during : abc - Time - Sat Nov 26 15:08:11 IST 2016
    pool-1-thread-1 Helloabc
    Doing a task during : def - Time - Sat Nov 26 15:08:16 IST 2016
    pool-1-thread-2 Hellodef
    Doing a task during : xyz - Time - Sat Nov 26 15:08:21 IST 2016
    pool-1-thread-1 Helloxyz
    Doing a task during : ritu - Time - Sat Nov 26 15:08:26 IST 2016
    pool-1-thread-3 Helloritu
    Doing a task during : babita - Time - Sat Nov 26 15:08:31 IST 2016
    pool-1-thread-2 Hellobabita
    

    代码:

    private String display(String name2) {
    
        try {
            //  System.out.println(Thread.currentThread().getName());
            name2=Thread.currentThread().getName()+" Hello"+ name;
            System.out.println("Doing a task during : " + name + " - Time - " + new Date());
            Thread.sleep(000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return name2;
    }
    
    
    @Override
    public String call() throws Exception {
        // TODO Auto-generated method stub
        if (name == "archana") {
    
            throw new Exception();
        }
            /*} catch (Exception e) {
                // TODO Auto-generated catch block
            //  e.printStackTrace();
            }finally{
                return "error";
            }*/
    
        return display(name);
    }
    
    public class ExecutorScheduleDemo {
    
        public static void main(String args[]) throws InterruptedException{
            ScheduledExecutorService executor= Executors.newScheduledThreadPool(5);
            ArrayList<Student> list = new ArrayList<Student>();
    
            list.add(new Student("prerna"));
            list.add(new Student("abc"));
            //list.add(new Student("archana"));
            list.add(new Student("def"));
            list.add(new Student("xyz"));
            list.add(new Student("ritu"));
            list.add(new Student("babita"));
            System.out.println("The time is : " + new Date());
            List<Future<String>> resultList= new  ArrayList<Future<String>>();
            for(Student s:list){
                Future<String> f=executor.schedule(s, 3, TimeUnit.SECONDS);
    
                try {
                    System.out.println(f.get());
                } catch (ExecutionException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    

2 个答案:

答案 0 :(得分:4)

使用scheduleAtFixedRate(Runnable, long initialDelay, long period, TimeUnit timeunit)代替schedule(Runnable task, long delay, TimeUnit timeunit)

  

scheduleAtFixedRate (Runnable, long initialDelay, long period, TimeUnit timeunit)
  创建并执行一个周期性操作,该操作在给定的初始延迟后首先启用,随后在给定的时间段内启用;执行将在initialDelay然后initialDelay+period,然后initialDelay + 2 * period之后开始,依此类推。如果任务的任何执行遇到异常,则后续执行被禁止。否则,任务将仅通过取消或终止执行者来终止。如果此任务的执行时间超过其周期,则后续执行可能会延迟,但不会同时执行。   下次执行。

答案 1 :(得分:0)

要完成eeedev的答案,因为您的对象似乎是Callable

您可以通过将FutureTask传递给构造函数来创建新的Callable,如oracle docs

中所述

请注意,FutureTask的type参数必须与Callable的相同。

示例:

class Main {

    public static void main(String[] args) {
        Foo foo = new Foo();
        FutureTask<String> fooFutureTask = new FutureTask<>(foo);
    }
}

class Foo implements Callable<String> {

    @Override
    public String call() throws Exception {
        return "Calling";
    }
}

然后,您可以按照eeedev。

的描述安排新创建的FutureTask执行
相关问题