O'Reilly logo

Java 11 Cookbook by Mohamed Sanaulla, Nick Samoylov

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 overrides 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 want the thread to generate a stream of integers in a certain range. Then, we use the peek() operation to invoke the doSomething() static method of the main class for each stream element in order to make the thread busy for some time. Refer to the following code:

int doSomething(int i){  IntStream.range(i, 100000).asDoubleStream().map(Math::sqrt).average();  return i;}

As you can see, the doSomething() ...

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