Java's Future multithreading Model

Source: Internet
Author: User

After Java 5, a large number of multi-threaded interfaces were provided. Previously, the thread pool was simply used, and the Future mode was also found recently.

Only some code is pasted:

Definition pool:

1. private static final ExecutorService worker = Executors. newFixedThreadPool (N); // Thread Pool

2. private static List

Use thread pool:

1. futureList. add (worker. submit (this ));

End thread:

1. // end the thread execution (interrupted) in the thread pool)

2. public static void cancel (){

3. for (Future f: futureList ){

4. f. cancel (true );

5 .}

6 .}

Note: Future is the thread execution result ticket. When Callable is used for execution, the thread execution result f. get () can be obtained, and the end and execution status of a thread can be controlled. When Runnable is used for execution, the result is null, but the thread can also be controlled.

Supplement:

The Thread interrupt method Thread. currentThread () should be called (). Interrupt (); but does not end the subthread as immediately as the stop method, but changes the interrupted semaphore Thread. interrupted (), an InterruptedException exception will be thrown in the blocked thread, but the sub-thread will continue to execute under non-blocking conditions. You need to determine the semaphore in the loop to throw an exception.

 

Author: xi_hong_shi
 

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.