Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How the JUC thread implements the Callable interface

Shulou Source: shulou.com Published: 2022-06-01 10:23:09 09月26日 Update

This article focuses on "how to implement the Callable interface with JUC threads". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how the Callable thread implements the JUC interface".

Java 5.0provides a new way to create execution threads in java.util.concurrent: the Callable interface

The Callable interface is similar to Runnable in that both are designed for classes whose instances can be executed by another thread. However, Runnable does not return a result and cannot throw a checked exception.

Callable depends on FutureTask, and FutureTask can also be used as a lock

Package com.gf.demo

Import java.util.concurrent.Callable

Import java.util.concurrent.ExecutionException

Import java.util.concurrent.FutureTask

/ * the third way to create a thread is to implement the Callable interface. Compared to the way the Runnable interface is implemented, a method can have a return value and can throw an exception. * * 2. To execute Callable, you need the support of FutureTask implementation class to accept the operation results. FutureTask is the implementation class of Future interface * * /

Public class TestCallable {public static void main (String args []) {ThreadDemo td = new ThreadDemo (); FutureTask result = new FutureTask (td); new Thread (result). Start (); try {Integer sum = result.get (); System.out.println (sum) System.out.println ("-");} catch (ExecutionException | InterruptedException e) {e.printStackTrace ();}

Class ThreadDemo implements Callable {@ Override public Integer call () throws Exception {int num = 0; for (int I = 0; I < Integer.MAX_VALUE; iTunes +) {num = num + I;} return num;}

} at this point, I believe you have a deeper understanding of "how JUC threads implement the Callable interface". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Interfaces threads methods contents methods results learning practicality deeper interest examples practicality practicality simplicity of operation more friends websites channels support query Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia MariaDB Shulou Information Huawei vpn