上篇回顾了一下FutureTask 的相关原理,现在分享一下它和消息队列的区别。
FutureTask
和消息队列都是用于处理并发任务的工具,但它们的应用场景和功能有很大的不同。以下是两者之间的主要区别:
FutureTask:
FutureTask
是一个实现了 RunnableFuture
接口的类,用于封装异步任务,并且能够获取任务的执行结果。消息队列:
FutureTask:
Callable
或 Runnable
对象,并由 FutureTask
执行。ExecutorService
提交 FutureTask
,任务会被线程池中的线程执行。FutureTask
的 get()
方法获取任务执行结果,或者通过 cancel()
方法取消任务。消息队列:
FutureTask:
消息队列:
FutureTask:
消息队列:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
public class FutureTaskExample {
public static void main(String[] args) {
Callable<String> callableTask = () -> {
Thread.sleep(2000);
return "Task completed";
};
FutureTask<String> futureTask = new FutureTask<>(callableTask);
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(futureTask);
System.out.println("Main thread is doing other work...");
try {
String result = futureTask.get();
System.out.println("FutureTask result: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executorService.shutdown();
}
}
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class RabbitMQExample {
private final static String QUEUE_NAME = "hello";
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
}
}
}
这两者各自有其独特的应用场景和优势,根据具体需求选择合适的工具。