线程池
2020-05-13 本文已影响0人
秋秋_6403
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();
}
}