Understanding the basic thread mechanism of java-18.2 from the beginning (3)-thread return and sleep

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.