java线程池_submit()

Posted 胡乐天

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java线程池_submit()相关的知识,希望对你有一定的参考价值。

submit()方法

有三个重载方法:

submit(Callable<T> task)//参数为Callable接口的实现类的实例
submit(Runnable task, T result)//第二个参数为默认值
submit(Runnable task)

线程池测试类

package com.thread.pool;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

public class TestExecuteAndSubmit {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executors = Executors.newFixedThreadPool(2);
        for (int i=0;i<10;i++){
            FutureTask futureTask = new FutureTask(TestCallable.getInstance());
            Object obj = "默认值";
            executors.submit(futureTask,obj);
            //此处打印futureTask.get(),所以线程会获得线程执行完成任务的结果,才会进入下一层循环
            System.out.println(futureTask.get());
        }
        executors.shutdown();

    }
}

#Callable接口测试类

package com.thread.pool;

import java.util.Date;
import java.util.concurrent.Callable;

public class TestCallable implements Callable {
    private static Callable callable;
    public static synchronized Callable getInstance(){
        if(callable == null){
            callable = new TestCallable();
        }
        return callable;
    }
    @Override
    public Object call() throws Exception {
        for (int i=0;i<10;i++){
            System.out.println((new Date()).toLocaleString() + "   " + Thread.currentThread().getName() + "执行" +i );
        }
        Thread.sleep(2000);
        return "return result";
    }
}

以上是关于java线程池_submit()的主要内容,如果未能解决你的问题,请参考以下文章

Java线程池中的execute和submit

一心多用多线程-细谈java线程池submit与execute的区别

Java Executor源码解析—ThreadPoolExecutor线程池submit方法以及FutureTask源码一万字

Java线程池中submit()和execute之间的区别?

13.ThreadPoolExecutor线程池之submit方法

线程池续:你必须要知道的线程池submit()实现原理之FutureTask!