提交(可运行)和提交(可召唤)的差异



bellow是实现可运行类的代码

public class ExecutorServiceWithRunnable {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(10);
        Future<emp> submit =null;
        emp emp = new emp();
        for(int i=0;i<5;i++) {
             submit = (Future<emp>) pool.submit(new RunnableClass(emp));
             try {
                    System.out.println(submit.get().getId());
                } catch (InterruptedException | ExecutionException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }

    }
}
class RunnableClass implements Runnable{
    emp e=null;
    public RunnableClass(emp emp) {
        // TODO Auto-generated constructor stub
        this.e=emp;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println(Thread.currentThread().getName()+"...."+e.getId());
        e.setId(e.getId()+1);
    }
}
class emp{
    int id;
    String status;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
}

删除put是:pool-1-thread-1...。java.lang.nullpoInterException在executorServiceWithRunnableCallable.main(executorServiceWithRunnable.java:15)

以下是可呼叫的代码

public class ExecutorServiceWithRunnableCallable2 {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(10);
        Future<emp> submit =null;
        emp emp = new emp();
        for(int i=0;i<5;i++) {
             submit = pool.submit(new CallableClass(emp));
             try {
                System.out.println(submit.get().getId());
            } catch (InterruptedException | ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
}
class CallableClass implements Callable<emp>{
    emp e=null;
    public CallableClass(emp emp) {
        // TODO Auto-generated constructor stub
        this.e=emp;
    }
    @Override
    public emp call() {
        // TODO Auto-generated method stub
        System.out.println(Thread.currentThread().getName()+"...."+e.getId());
        e.setId(e.getId()+1);
        return e;
    }
}

**获得输出是:** pool-1-thread-1 .... 01pool-1-thread-2 .... 12pool-1-thread-3 .... 23pool-1-thread-4 .... 34pool-1-thread-5 .... 45

因此,在两种情况下由提交方法返回的未来对象澄清我。

a Runnable不会返回结果。因此,Future::get仍将阻止直到完成运行,但只需返回null

submit = (Future<emp>) pool.submit(new RunnableClass(emp));

此类铸造将产生警告,因为您实际上没有在这里获得Future<emp>。而且因为您忽略了这一点,所以您稍后会得到例外。

就像Javadoc所说的那样,您确实得到了Future<?>,这意味着(在这种情况下)您不能使用结果值。

submit = pool.submit(new CallableClass(emp));

如果您想要结果,请提交一个可可。请注意,不需要类,它可以从可可的类型中推断出未来的通用类型。

相关内容

  • 没有找到相关文章

最新更新