多线程-使用线程池(八)
-
使用线程池
- JDK5.0起提供了线程池相关API:ExecutorService和Executors
- ExecutorService:真正的线程池接口。常见子类,ThreadPoolExecutor
- void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable
- Futuresubmit(Callable task):执行任务,有返回值,一般用来执行Callable
- void shutdown():关闭连接池
- Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池
-
使用线程池具体的实现1:
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()); //2.关闭连接 service.shutdown(); } } class MyThread implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()); } }
-
使用线程池具体的实现2:
import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.concurrent.*; //线程方式三:实现callable接口 /** callable的好处 1.可以定义返回值 2.可以跑出异常 */ public class TestCallable implements Callable<Boolean> { private String url;//网络图片地址 private String name;//保存的文件名 public TestCallable(String url,String name){ this.url=url; this.name=name; } //下载图片的执行体 @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 t1=new TestCallable("https://img-blog.csdnimg.cn/20210316213155604.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1h1bl9pbmRlcGVuZGVudA==,size_16,color_FFFFFF,t_70#pic_center","1.jpg"); TestCallable t2=new TestCallable("https://img-blog.csdnimg.cn/20210316213209625.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1h1bl9pbmRlcGVuZGVudA==,size_16,color_FFFFFF,t_70#pic_center","2.jpg"); TestCallable t3=new TestCallable("https://img-blog.csdnimg.cn/20210316213228816.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1h1bl9pbmRlcGVuZGVudA==,size_16,color_FFFFFF,t_70#pic_center","3.jpg"); //创建执行服务: ExecutorService ser= Executors.newFixedThreadPool(3);//搞了一个线程池,先了解,以后会讲 //提交执行 Future<Boolean> r1=ser.submit(t1); Future<Boolean> r2=ser.submit(t2); Future<Boolean> r3=ser.submit(t3); //获取结果 boolean rs1=r1.get(); boolean rs2=r2.get(); boolean rs3=r3.get(); System.out.println(rs1); System.out.println(rs2); System.out.println(rs3); //关闭服务 ser.shutdownNow(); } } //下载器 class WebDownloader{ //下载方法 public void downloader(String url,String name){ try { FileUtils.copyURLToFile(new URL(url),new File(name)); } catch (IOException e) { e.printStackTrace(); System.out.println("IO异常,downloader方法出现问题"); } } }