O'Reilly logo

Java 9 Cookbook by Nick Samoylov, Mohamed Sanaulla

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

First, we create a class called AThread that extends Thread and override its run() method: 

class AThread extends Thread {  int i1,i2;  AThread(int i1, int i2){    this.i1 = i1;    this.i2 = i2;  }  public void run() {    IntStream.range(i1, i2)             .peek(Chapter07Concurrency::doSomething)             .forEach(System.out::println);  }}

In this example, we wanted the thread to generate a stream of integers in a certain range. Then, we peeked into each emitted integer (the method peek() cannot change the stream element) and called the static method doSomething() of the main class in order to make the thread busy for some time. Refer to the following code:

private static int doSomething(int i){  IntStream.range(i, 99999).asDoubleStream().map(Math::sqrt).average() ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required