提问者:小点点

Java 8-用多个参数调用方法


我已经用了一段时间的Java 8流。 我遇到过这样一种情况,我需要流式遍历一个列表,并将每个元素传递给一个类的方法,该方法不是静态的。

List<String> emps = new ArrayList<>();
emps.add("ABC");
emps.add("DEF");
emps.add("GHI");

我想调用EmpDataGenerator的“start”方法。

EmpDataGenerator generator = new EmpDataGenerator(
                Executors.newFixedThreadPool(emps.size()));

我试过了,但不起作用

emps.stream().map(e-> generator.start(e));

public class EmpDataGenerator {

    // Used to signal a graceful shutdown
    private volatile boolean stop = false;
    private final ExecutorService executor;

    public EmpDataGenerator(ExecutorService executor) {
        this.executor = executor;
    }

    public void start(Sting name ) {
        Runnable generator = () -> {
            try {
                while (!stop) {
                    //do some processing
                 }
                System.out.println("Broke while loop, stop " + stop);
            } catch (Exception e) {
                System.out.println("EmpDataGenerator thread caught an exception and halted!");
                throw e;
            }
        };
        executor.execute(generator);
    }

    public void stop() {
        stop = true;

        // The shutdown the executor (after waiting a bit to be nice)
        try {
            executor.awaitTermination(1000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            // Purposely ignore any InterruptedException
            Thread.currentThread().interrupt();
        }
        executor.shutdownNow();
    }

}

共1个答案

匿名用户

映射必须接受输入并将其转换为某种东西。 start方法无效。

这里不需要溪流。 一个简单的foreach就可以了。

emps.forEach(e-> generator.start(e)); 

emps.forEach(generator::start);