Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the Future multithreading mode of Java

Shulou Source: shulou.com Published: 2022-06-02 05:09:45 09月19日 Update

This article introduces the relevant knowledge of "how to use Java's Future multithreading mode". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

After Java5, it provides a large number of interfaces for dealing with multithreading, which used to be simple to use its thread pool, and recently found that the Future pattern also exists.

Only part of the code is posted:

Define the pool:

Private static final ExecutorService worker = Executors.newFixedThreadPool (N); / / Thread pool private static List > (); / / working threads

Use thread pools:

FutureList.add (worker.submit (this))

End thread:

/ / end thread execution (interrupt) public static void cancel () {for (Future f: futureList) {f.cancel (true);}} in the thread pool

Note: Future is the ticket for the execution result of a thread. When executing in Callable mode, you can get the execution result of a thread f.get (). At the same time, you can also control the end and execution state of a thread. When executed in Runnable mode, the result is empty, but the thread can also be controlled.

Add:

The interrupt method Thread.currentThread (). Interrupt () of the thread should be called; but instead of ending the drop child thread immediately as the stop method does, it changes the semaphore of the interrupt Thread.interrupted (). The blocked thread will throw an InterruptedException exception, but under non-blocking conditions, the child thread will continue to execute and need to judge the semaphore in the loop to throw the exception.

This is the end of the content of "how to use Java's Future multithreading mode". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Threads patterns results signals contents ways methods more knowledge semaphores control blocking practicality learning and then code just at the same time dilemma reality. Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Shulou Technology Shulou Information Xiaomi MySQL