多线程之线程池的两种使用方法

在这里插入图片描述在这里插入图片描述代码:

package com.qiu.syn;

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

//测试线程池
public class TestPool {
    public static void main(String[] args) {
        //1.创建线程池,创建服务
        //newFixedThreadPool 参数为线程池大小
        ExecutorService service = Executors.newFixedThreadPool(10);
        //执行
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());//关闭连接

​        service.shutdown();}
}
class MyThread implements Runnable{@Overridepublic void run() {for (int i = 0; i < 100; i++) {
​            System.out.println(Thread.currentThread().getName()+":"+i);}}
}

Callable需要用submit执行:

package com.qiu.demo02;

import com.qiu.demo01.TestThread02;
import com.qiu.demo01.webDownloader;


import java.util.concurrent.*;


//练习thread,实现多线程同步下载图片
    public class TestCallable implements Callable<Boolean> {
        private String url;//网络图片地址
        private String name;//保存的文件名
        public TestCallable(String url,String name){
            this.name=name;
            this.url=url;
        }
        @Override
        //线程的执行体
        public Boolean call() {
            webDownloader webDownloader = new webDownloader();
            webDownloader.downloader(url,name);
            System.out.println("下载的文件名为" +name);
            return true;
        }
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            TestCallable testCallable = new TestCallable("https://ww1.sinaimg.cn/bmiddle/006cNziigy1ge44slsqkuj31400u0tc1.jpg","1.jpg");
            TestCallable testCallable1 = new TestCallable("https://ww1.sinaimg.cn/bmiddle/006cNziigy1ge44slsqkuj31400u0tc1.jpg","2.jpg");
            TestCallable testCallable2 = new TestCallable("https://ww1.sinaimg.cn/bmiddle/006cNziigy1ge44slsqkuj31400u0tc1.jpg","3.jpg");//创建执行服务
​            ExecutorService ser = Executors.newFixedThreadPool(3);//提交查询 对比Run方法
​            Future<Boolean> result1 = ser.submit(testCallable);
​            Future<Boolean> result2 = ser.submit(testCallable1);
​            Future<Boolean> result3 = ser.submit(testCallable2);//获取结果
​            Boolean r1 = result1.get();
​            Boolean r2 = result2.get();
​            Boolean r3 = result3.get();//关闭服务
​            ser.shutdown();}}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值