线程池

mac2022-06-30  33

package cn.itcast.demo16.Demo12.ThreadPool;/** * @author newcityman * @date 2019/7/25 - 23:47 */public class RunnableImpl implements Runnable {@Override public void run() { System.out.println(Thread.currentThread().getName()+"---->创建了一个新的线程"); }} package cn.itcast.demo16.Demo12.ThreadPool;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * @author newcityman * @date 2019/7/25 - 23:26 * java.util.concurrent.Executors:线程池的工厂类,用来生成线程池, * Executors类中的静态方法: * static ExecutorService newFixedThreadPool(int nThread) 创建一个可重用固定线程数量的线程池 * 参数: * int nThreads:创建线程池中包含的线程数量 * 返回值: * ExecutorService接口,返回的是ExecutorService接口的实现类对象,我们可以使用ExecutorService接口接受 * java.util.concurrent.ExecutorService:线程池接口 * 用来从线程池中获取线程,调用start方法,执行线程任务 * submit(Runnable tstk)提交一个Runnable任务用于执行 * 关闭/销毁线程池的方法 * void shutdown(); * 1、使用线程池的工厂类Executors里面提供的静态方法newFixedThreadPool生产一个指定线程数量的线程池 * 2、创建一个类,实现Runnable接口,重写run方法,设置线程任务 * 3、调用ExecutorService中的方法submit,传递线程任务(实现类),开启线程,执行run方法 * 4、调用ExecutorService中的方法shutdown销毁线程池(不建议使用) */public class Demo01ThreadPool {public static void main(String[] args) {// 1、使用线程池的工厂类Executors里面提供的静态方法newFixedThreadPool生产一个指定线程数量的线程池 ExecutorService es = Executors.newFixedThreadPool(2);// 3、调用ExecutorService中的方法submit,传递线程任务(实现类),开启线程,执行run方法 es.submit(new RunnableImpl()); es.submit(new RunnableImpl()); es.submit(new RunnableImpl());// 4、调用ExecutorService中的方法shutdown销毁线程池(不建议使用) es.shutdown(); }}

转载于:https://www.cnblogs.com/newcityboy/p/11247797.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)