当前位置:网站首页>Get the thread return value. Introduction to the use of future interface and futuretask class

Get the thread return value. Introduction to the use of future interface and futuretask class

2022-04-23 14:14:00 pureluckyfish

        Start a thread , Computer according to cpu And memory usage , Execute code in the thread at a future point in time . How do I know if the thread execution is complete , What's the result ?Future English means “ future 、 Future ”, seeing the name of a thing one thinks of its function Future Interface came into being .
        One 、Future The interface is introduced

        Usage method get Search , Block if necessary , Until it's ready .cancel Cancel the operation . Other methods are provided to determine whether the task is completed normally or cancelled . Once the calculation is done , We can't cancel the calculation . If used for cancellability Future, But do not provide available results , It can be stated that Future>, And back to null As a result of the underlying task .

Return value Method name Method usage description
boolean cancel(boolean mayInterruptIfRunning) Attempt to cancel the execution of this task . If the task has been completed 、 Has been cancelled or cannot be cancelled for other reasons , Then the attempt will fail . If it works , And calling cancel The task did not start when , The task should never run . If the task has been started , be mayInterruptIfRunning Parameter determines whether the thread executing the task should be interrupted to try to stop the task
boolean isCancelled() If this task is cancelled before normal completion , Then return to true
boolean isDone() If this task is completed, return to true
V get() Get thread execution results , Will be waiting , Until the thread execution is complete
V get(long timeout, TimeUnit unit) Get thread execution results , If no result is obtained within the specified time, an exception will be thrown

Two 、Future Code example

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

public class Future_FutureTask {
	// Creating a thread pool 
	ExecutorService exec = Executors.newCachedThreadPool();

	@Test
	public void FutureTest() throws Exception {
		// return Future
		Future<?> future = exec.submit(() -> {
			System.out.println("Runnabel Interface , No return value ");
		});
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		if (future.isDone()) {
			System.out.println(" Get thread return result :" + future.get());
		} else {
			System.out.println(" Get thread return result :" + future.get(10L, TimeUnit.SECONDS));
		}
		System.out.println(" Whether the thread is cancelled " + future.isCancelled());

	}
}

3、 ... and 、FutureTask Introduction to implementation class

         This class provides Future The basic implementation of the interface ;FutureTask Can be used to package into  Callable  perhaps  Runnable  Object to use . because FutureTask Realized Runnable Interface , therefore FutureTask Can be submitted to Executor perform

Four 、FutureTask Code example

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

public class Future_FutureTask {
	//  Creating a thread pool 
	ExecutorService exec = Executors.newCachedThreadPool();

	@Test
	public void FutureTaskTest() throws Exception {
		//  Use Lambda  Create objects using expressions 
		// FutureTask<V> futureTask = new FutureTask<V>(Callable<V> callable)
		FutureTask<String> futureTask = new FutureTask<String>(() -> {
			return "FutureTask Introduction ";
		});
		exec.execute(futureTask);
		System.out.println(" obtain FutureTask Return result of :" + futureTask.get());

	}
}

5、 ... and 、 summary

        Future Express Asynchronous computation ( Threads ) Result . The method provided is used to check whether the calculation is completed 、 Wait for it to complete and retrieve the results of the calculation .

        FutureTask Class is Future Implementation class of interface

版权声明
本文为[pureluckyfish]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231406486464.html