美文网首页
java并发包

java并发包

作者: 扎Zn了老Fe | 来源:发表于2019-01-20 16:05 被阅读0次

知识体系

image.png

使用多线程可以将多个执行任务同时执行,加快计算机处理速度。在java中,已经有了多线程执行框架,下面将简单介绍。

Runnable

public interface Runnable {
    public abstract void run();
}

Callable

public interface Callable<V> {
    V call() throws Exception;
}

Runnable和Callable两者不同点是:

  1. 实现Callable接口的任务线程能返回执行结果;而实现Runnable接口的任务线程不能返回结果;
  2. 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

相关文章

网友评论

      本文标题:java并发包

      本文链接:https://www.haomeiwen.com/subject/pjvxrqtx.html