代码:
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{
@Override
public 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();
}
}