Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Implementation method of self-defined FutureTask

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "the implementation of custom FutureTask", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "the implementation of custom FutureTask" bar!

FutureTask

FutureTask is the implementation of Future, which is used to obtain the results of asynchronous tasks, to start and cancel asynchronous tasks, to query whether the calculation of asynchronous tasks is finished, and to obtain the results of the final asynchronous tasks. The result of the asynchronous task is obtained through the get () method, but blocks the current thread until the asynchronous task is finished. Once the task execution is finished, the task cannot be restarted or cancelled unless the runAndReset () method is called.

Code example:

Public class ThreadTest {public static void main (String [] args) throws Exception {Callable myCallable = new MyCallableThread (); FutureTask futureTask = new FutureTask (myCallable); Thread myCallableThread = new Thread (futureTask); myCallableThread.setName ("MyThread-implements-Callable-test"); myCallableThread.start (); System.out.println ("Run by Thread:" + futureTask.get ()); / / execute ExecutorService executorService = Executors.newCachedThreadPool () through the thread pool; executorService.submit (futureTask) ExecutorService.shutdown (); System.out.println ("Run by ExecutorService:" + futureTask.get ());}} class MyCallableThread implements Callable {@ Override public String call () throws Exception {return Thread.currentThread (). GetName ();}} implement your own FutureTask

According to the core principles of FutureTask, to implement a FutureTask, the following aspects must be met:

A generic definition is required to return the result type

A callable object is required, which is passed in the constructor

It is necessary to implement the runnable interface and realize the concrete result calculation in the run method.

A public get method is required to get the results

If the thread does not finish executing, the thread calling the get method needs to enter the waiting queue

A field is required to record the status of thread execution

Need a thread that waits for the queue to store the waiting results

Code example:

/ * 1. Generic definition * 2. Construction method callable * 3. Runnable * 4. Get method returns callable execution result * 5. Get method has blocking effect (if the execution is not finished) * / public class MyFutureTask implements Runnable {/ / the result of program execution private T result; / / the task to be executed private Callable callable; / / the status of the task running private volatile int state = NEW; / / the status value of the task running private static final int NEW = 0; private static final int RUNNING = 1 Private static final int FINISHED = 2; / the thread waiting for the result LinkedBlockingQueue waiters = new LinkedBlockingQueue; / / the thread executing the current FutureTask competes with CAS for AtomicReference runner = new AtomicReference (); public MyFutureTask (Callable task) {this.callable = task } @ Override public void run () {/ / determine the status of the current object, and execute if (state! = NEW | |! runner.compareAndSet (null, Thread.currentThread ()) return; state = RUNNING; try {result = callable.call ();} catch (Exception e) {e.printStackTrace ();} finally {state = FINISHED) if it is RUNNING; try } / / after the method is executed, wake up all threads while (true) {Thread waiterThread = waiters.poll (); if (waiterThread = = null) break; LockSupport.unpark (waiterThread);} public T get () {/ / if the state is not FINISHED, enter the waiting queue if (state! = FINISHED) {waiters.offer (Thread.currentThread ()) } while (state! = FINISHED) {LockSupport.park ();} return result;}} / / MyFutureTask Test public class FutureTaskTest {public static void main (String [] args) {Callable myCallable = new MyCallableThread (); MyFutureTask futureTask = new MyFutureTask (myCallable); Thread myCallableThread = new Thread (futureTask); myCallableThread.setName ("MyFutureTask-test"); myCallableThread.start (); System.out.println ("Run by Thread:" + futureTask.get ()) }} class MyCallableThread implements Callable {@ Override public String call () throws Exception {return Thread.currentThread (). GetName ();}} at this point, I believe you have a deeper understanding of "the implementation of custom FutureTask". 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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report