In the below example, I am using the field number
in IntStream.range(0, 10).forEach(number -> new Thread(r).start());
even though it is not being used. Is there a way to rewrite it so that I do not have to use the unused number variable?
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++;
}
}