java接口ExecutorService有几个提交方法,它们接受Runnable或Callable任务作为参数。我可以传递对象方法吗?

时间:2017-06-25 09:19:28

标签: java java.util.concurrent

界面java.util.concurrent.ExecutorService有多个submit方法,submit 第二个接受Runnable任务参数。但是,我看到了一些这样的代码,首先是Counter类:

public class Counter {
    private int count;
    public void increment() {
        count++;
    }
    public int getCount() {
        return count;
    }
}

Demo类:

public class Demo {
    private Counter counter = new Counter();
    public void demoCounter() {
        ExecutorService service = Executors.newCachedThreadPool();
        IntStream.range(0, 1000)
            forEach(i -> service.submit(counter:: increment));
        service.shutdown();
        System.out.println("Counter count=" + counter.getCount());
    }
    public void main(String[] args) {
        Demo demo = new Demo();
        demo.demoCounter();
    }
}

我想知道在Demo类中,提交方法的参数是counter:: increment,我认为它不是Runnable任务对象。那么,有什么神奇的事情发生了吗?

0 个答案:

没有答案