Java创建多线程方式四:使用线程池
使用线程池的方法是开发中最为常用的创建多线程的方法,主要步骤有:
1.在main方法中调用Executors.newFixedThreadPool(10)方法,指定创建线程的数量,alt+enter,用ExecutorService类型的接住,比如此线程叫做service。此处体现了多态,ExecutorService实际上是一个接口,所以其返回值是其实现类。利用getClass可以知道,其返回值得类是ThreadPoolExecutor。
2.执行指定线程得操作。
service.execute(Runnable接口的实现类对象);适用于Runnable接口,形参处传入Runnable接口实现类的对象。
service.submit(Callable callable);适用于Callable接口
3.线程结束后,要对线程进行释放,关闭连接池。service.shutdown
注:如果想设置线程的属性,需要对ExecutorService类型的对象进行向下转型(强转),因为ExecutorService是一个接口,接口不可以实例化,所以只能通过其实现类调用方法,所以这里只能先强转成为其实现类ThreadPoolExecutor,然后再对属性进行操作。这几个的继承实现关系如图:
package java2; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; /** * 创建线程的方式四:线程池 * * 好处: * 1.提高响应速度 * 2.降低资源消耗 * 3.便于线程管理 * corePoolSize:核心池大小 * maximumPoolSize:最大线程数 * keepAliveTime:线程没有任务时,最多保持多长时间后会停止 * 面试题:创建多线程有几种方式:四种 * @author * @create 2022-01-11-9:28 */ class NumberThread implements Runnable{ @Override public void run() { for (int i = 0; i <= 100; i++) { if(i%2==0){ System.out.println(Thread.currentThread().getName()+":"+i); } } } } class NumberThread1 implements Runnable{ @Override public void run() { for (int i = 0; i <= 100; i++) { if(i%2!=0){ System.out.println(Thread.currentThread().getName()+":"+i); } } } } public class ThreadPool { public static void main(String[] args) { //1.提供指定线程数量的线程池 ExecutorService service = Executors.newFixedThreadPool(10); //设置线程池的属性,需要先进行强转(向下转型),因为接口中不可以用对象.方法调用 ThreadPoolExecutor service1= (ThreadPoolExecutor) service; service1.setCorePoolSize(10); service1.setMaximumPoolSize(10); //2.执行指定线程的操作,提供指定实现Runnable接口或实现Callable接口的对象 service.execute(new NumberThread());//适合适用于Runnable service.execute(new NumberThread1());//适合适用于Runnable // service.submit(Callable callable);//适合适用于Callable //3.关闭连接池 service.shutdown(); } }
下一篇:
构造器的基本理解和JavaBean