迭代 IntStream 以打印值

Pun*_*cky 0 java java-stream java-threads

在下面的示例中,我正在使用该字段,number即使IntStream.range(0, 10).forEach(number -> new Thread(r).start());它没有被使用。有没有办法重写它,以便我不必使用未使用的数字变量?

    import javax.annotation.concurrent.NotThreadSafe;
    import java.util.stream.IntStream;
    
    public class LearnThreads {
        public static void main(String[] args)  {
            UnsafeThreadClass counter = new UnsafeThreadClass();
            Runnable r = () -> {
                try {
                    System.out.println(counter.getValue() + " : Thread - " +Thread.currentThread());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            };
            IntStream.range(0, 10).forEach(number -> new Thread(r).start());
        }
    }
    
    
    @NotThreadSafe
    class UnsafeThreadClass {
        private int value;
    
        public synchronized int getValue() throws InterruptedException {
            Thread.sleep(1000);
            return value++;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Boh*_*ian 8

不; 您必须为消费者的参数指定一个名称,但是为什么要使用流呢?

这更简单且更具可读性:

for (int i = 0; i < 10; i++) {
    new Thread(r).start();
}
Run Code Online (Sandbox Code Playgroud)

如果您必须使用 Stream,请尝试limit()

Stream.generate(() -> new Thread(r)).limit(10).forEach(Thread::start);
Run Code Online (Sandbox Code Playgroud)

但那里有一个丑陋的制片人。