简体   繁体   English

将方法提交到ExecutorService Java

[英]Submitting method into ExecutorService Java

So I have this code here, that adds my "NamePrinter" runnable class as ExecutorService tasks. 所以我在这里有这个代码,它将我的“NamePrinter”runnable类添加为ExecutorService任务。 Everything works fine, but I'd like to get rid of that extra class. 一切都很好,但我想摆脱额外的课程。 So I am asking is there a way to submit method to ExexutorService? 所以我想问有没有办法向ExexutorService提交方法?

Here is the code that I currently have: 这是我目前的代码:

public void start(){
        Collection<Future<?>> futures = new LinkedList<>();
        final ExecutorService es = Executors.newFixedThreadPool(poolSize);

        for (int i = 0; i < 10; i++) {
        futures.add(es.submit(new NamePrinter(name)));
        }

        es.shutdown();
}

But I'd like it to be something like this: 但我希望它是这样的:

public void start(){
            Collection<Future<?>> futures = new LinkedList<>();
            final ExecutorService es = Executors.newFixedThreadPool(poolSize);

            for (int i = 0; i < 10; i++) {
            futures.add(es.submit(namePrint(i+"name"))); // This code doesn't work, I just made it so you could understand what I mean.
            }

            es.shutdown();
    }

public void namePrint(String name){  // I'd like this to be the task that ExecutorService runs.

System.out.println(name);

}

Is this something that is possible to achieve? 这是可以实现的吗?

The closest you can come as an anonymous inner class: 最接近你可以作为匿名内部类来:

for (int i = 0; i < 10; i++) {
    final int x = i;
    futures.add(es.submit(new Runnable() {
        @Override public void run() {
            namePrint(x + "name");
        }
    }));
}

You are essentially asking: is Java supporting functions as first class citizens (sometimes it is refered as closures or lambdas ) - no, you can't do this in Java . 你本质上是在问: Java是否支持函数作为一等公民 (有时它被称为闭包lambdas ) - 不, 你不能用Java做到这一点 You can in Groovy, Scala, JavaScript, C#... but not in Java. 您可以使用Groovy,Scala,JavaScript,C#...但不能使用Java。

Your NamePrinter class (probably implementing Runnable or Callable ) is the closest you can get in Java and this is the Java way (or you can use anonymous inner class). 您的NamePrinter类(可能实现RunnableCallable )是您在Java中最接近的,这是Java方式(或者您可以使用匿名内部类)。

In this specific case, I think you'll not be able to do exactly what you want, because the run method of Runnable interface doesn't take any arguments. 在这种特定情况下,我认为你无法完全按照自己的意愿Runnable ,因为Runnable接口的run方法不接受任何参数。 However, you can use lambda expressions since Java 8 . 但是,您可以在Java 8之后使用lambda表达式 So you have few options now: 所以你现在几乎没有选择:

1 - Define the method on-the-fly 1 - 即时定义方法

final String name = "whatever";

exServ.execute(() -> {            
    System.out.println(name);
});

2 - Define a static method and then use static method reference 2 - 定义静态方法,然后使用静态方法引用

public static void printName()
{
    System.out.println(ClassNameX.name);
}

exServ.execute(ClassTest::printName);

3 - Create an instance of your NamePrinter class - which doesn't need to implement the Runnable interface - to store the parameters and then use instance method reference. 3 - 创建NamePrinter类的实例 - 不需要实现Runnable接口 - 来存储参数,然后使用实例方法引用。

NamePrinter np = new NamePrinter("testName");

exServ.execute(np::namePrint);

There are some options for this: 有一些选择:

  1. Using anonymous class 使用匿名类

     es.submit { new Runnable() { public void run() { //do your stuff here } }); 
  2. Use languages which support closures like Scala . 使用支持Scala等闭包的语言。 However the API must support this, which ExecutorService doesn't. 但是,API必须支持此功能,ExecutorService不支持此功能。

  3. Wait for Java 8 which will introduce closures. 等待Java 8 ,这将引入闭包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM