知识体系
image.png使用多线程可以将多个执行任务同时执行,加快计算机处理速度。在java中,已经有了多线程执行框架,下面将简单介绍。
Runnable
public interface Runnable {
public abstract void run();
}
Callable
public interface Callable<V> {
V call() throws Exception;
}
Runnable和Callable两者不同点是:
- 实现Callable接口的任务线程能返回执行结果;而实现Runnable接口的任务线程不能返回结果;
- Callable接口的call()方法允许抛出异常;而Runnable接口的run()方法的异常只能在内部消化,不能继续上抛;
ExecutorService
public interface ExecutorService extends Executor {
void execute(Runnable command);
Future<?> submit(Runnable task);
<T> Future<T> submit(Callable<T> task);
<T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException;
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) InterruptedException;
}
Future
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning)
V get();
V get(long timeout, TimeUnit unit);
boolean isCancelled();
boolean isDone();
}
示例
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* @since 2019/1/20 下午4:10
*/
public class MultiThreadDemo {
public static ExecutorService executorService = Executors.newCachedThreadPool();
public static void main(String[] args) {
try {
executorService.execute(new Runnable() {
public void run() {
System.out.println("run Runnable task");
}
});
Future future = executorService.submit(new Runnable() {
public void run() {
System.out.println("submit Runnable task");
}
});
System.out.println(future.get());
Future future2 = executorService.submit(new Callable(){
public String call() throws Exception {
System.out.println("submit Callable task");
return "Callable Result";
}
});
System.out.println("future.get() = " + future2.get() + " type: " + future2.getClass());
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
参考资料:
[1]. https://blog.csdn.net/wbwjx/article/details/51156125
[2]. http://tutorials.jenkov.com/java-util-concurrent/java-future.html
网友评论