线程池

image

不要忘记关闭服务

execute,执行实现runnable接口的对象

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

public class TestThreadPool implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());

    }

    public static void main(String[] args) {

        ExecutorService service = Executors.newFixedThreadPool(3);
        service.execute(new TestThreadPool());
        service.execute(new TestThreadPool());
        service.execute(new TestThreadPool());
        service.shutdown();

    }
}

submit,执行实现callable的对象

import util.WebDownloader;

import javax.sql.rowset.CachedRowSet;
import java.util.concurrent.*;

public class TestCallable implements Callable {

    private String url;
    private String name;

    public TestCallable(String url, String name) {
        this.url = url;
        this.name = name;
    }

    @Override
    public Integer call() throws Exception {
        WebDownloader downloader = new WebDownloader();
        downloader.download(url, name);
        System.out.println(name + "下载成功");

        return 1;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable callable = new TestCallable("http://www.baidu.com/img/bd_logo1.png", "image1.jpg");
        TestCallable callable2 = new TestCallable("http://www.baidu.com/img/bd_logo1.png", "image2.jpg");

        TestCallable callable3 = new TestCallable("http://www.baidu.com/img/bd_logo1.png", "image3.jpg");

        //创建执行服务
        ExecutorService service = Executors.newFixedThreadPool(3);
        //提交执行,相当于start()
        Future<Integer> result1 = service.submit(callable);
        Future<Integer> result2 = service.submit(callable2);
        Future<Integer> result3 = service.submit(callable3);
        //获取结果
        System.out.println(result1.get());
        System.out.println(result2.get());
        System.out.println(result3.get());
        //关闭服务
        service.shutdown();


    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容