微信登录

多线程 - 方式四 - 线程池

  1. package com.atguigu.java2;
  2. import java.util.concurrent.ExecutorService;
  3. import java.util.concurrent.Executors;
  4. import java.util.concurrent.ThreadPoolExecutor;
  5. /**
  6. * 创建线程的方式四:使用线程池
  7. *
  8. * 好处:
  9. * 1.提高响应速度(减少了创建新线程的时间)
  10. * 2.降低资源消耗(重复利用线程池中线程,不需要每次都创建)
  11. * 3.便于线程管理
  12. * corePoolSize:核心池的大小
  13. * maximumPoolSize:最大线程数
  14. * keepAliveTime:线程没有任务时最多保持多长时间后会终止
  15. *
  16. *
  17. * 面试题:创建多线程有几种方式?四种!
  18. * @author shkstart
  19. * @create 2019-02-15 下午 6:30
  20. */
  21. class NumberThread implements Runnable{
  22. @Override
  23. public void run() {
  24. for(int i = 0;i <= 100;i++){
  25. if(i % 2 == 0){
  26. System.out.println(Thread.currentThread().getName() + ": " + i);
  27. }
  28. }
  29. }
  30. }
  31. class NumberThread1 implements Runnable{
  32. @Override
  33. public void run() {
  34. for(int i = 0;i <= 100;i++){
  35. if(i % 2 != 0){
  36. System.out.println(Thread.currentThread().getName() + ": " + i);
  37. }
  38. }
  39. }
  40. }
  41. public class ThreadPool {
  42. public static void main(String[] args) {
  43. //1. 提供指定线程数量的线程池
  44. ExecutorService service = Executors.newFixedThreadPool(10);
  45. ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;
  46. //设置线程池的属性
  47. // System.out.println(service.getClass());
  48. // service1.setCorePoolSize(15);
  49. // service1.setKeepAliveTime();
  50. //2.执行指定的线程的操作。需要提供实现Runnable接口或Callable接口实现类的对象
  51. service.execute(new NumberThread());//适合适用于Runnable
  52. service.execute(new NumberThread1());//适合适用于Runnable
  53. // service.submit(Callable callable);//适合使用于Callable
  54. //3.关闭连接池
  55. service.shutdown();
  56. }
  57. }