首页 > 学院 > 开发设计 > 正文

Thread -线程池

2019-11-06 06:20:55
字体:
来源:转载
供稿:网友
package day04;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * 线程池 * 作用: * 1:控制线程数量 * 2:重用线程 * @author Administrator * */public class ThreadPoolDemo { public static void main(String[] args) { //创建一个固定大小的线程池 ExecutorService threadPool = Executors.newFixedThreadPool(2); //指派5个任务给线程池 for(int i=0;i<5;i++){ Runnable runn = new Runnable(){ public void run(){ Thread t = Thread.currentThread(); System.out.PRintln( t.getName()+"正在运行任务.."); try { Thread.sleep(5000); } catch (InterruptedException e){ } System.out.println( t.getName()+"执行完任务了.."); } }; //将任务交给线程池 threadPool.execute(runn); } threadPool.shutdownNow(); }}

运行结果:

pool-1-thread-1正在运行任务...pool-1-thread-2正在运行任务...pool-1-thread-1执行完任务了..pool-1-thread-1正在运行任务...pool-1-thread-2执行完任务了..pool-1-thread-2正在运行任务...pool-1-thread-1执行完任务了..pool-1-thread-1正在运行任务...pool-1-thread-2执行完任务了..pool-1-thread-1执行完任务了..
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表