Understanding the basic thread mechanism of java-18.2 from the beginning (3)-thread return and sleep
In this section, we will discuss the thread return and sleep.
1. Thread return
package com.ray.ch17;import java.util.Random;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;public class Test {public static void main(String[] args) throws InterruptedException,ExecutionException {ExecutorService executors = Executors.newFixedThreadPool(2);Callable
callable = new MyCall();for (int i = 0; i < 10; i++) {Future
future = executors.submit(callable);System.out.println(future.get());}}}class MyCall implements Callable
{@Overridepublic Integer call() throws Exception {System.out.println("doing something...");Thread.sleep(1000);return new Random().nextInt(50);}}
Output:
Doing something...
34
Doing something...
2
Doing something...
10
Doing something...
11
Doing something...
10
Doing something...
28
Doing something...
21
Doing something...
29
Doing something...
25
Doing something...
0
In the previous article, I first learned about the content in java-17.6 Callable, ure, and FutureTask.
2. sleep
If you run the above Code, you will obviously feel that every output will pause. This is the role of sleep.
Summary: This chapter mainly describes the thread return and sleep.