Java的线程池

信号灯

  • 并发协作模型:生产者/消费者模式-->信号灯法(判断标志位)

package com.kuang.hyperprocess;
//测试生产者消费者问题2:信号灯法,通过标志位解决。
public class TestPc2{
   public static void main(String[] args){
       TV tv = new TV();
       new Player(tv).start();
       new Watcher(tv).start();
  }
}
//生产者-->演员
class Player extends Thread{
   private TV tv;
   public Player(TV tv){
       this.tv = tv;
  }
   @Override
   public void run(){
       for (int i=0; i<20; i++){
           if (i % 2 == 0){
               this.tv.play("中国有C哈")
          }else{
               this.tv.play("抖音 记录美好生活");
          }
      }
  }
}
//消费者-->观众
class Watcher extends Thread{
   TV tv;
   public Wathcer(TV tv){
       this.tv = tv;
  }
   @Override
   public void run(){
       for (int i=0; i<20; i++){
           tv.watch();
      }
  }
}
//产品-->节目
class TV{
   //演员表演 观众等待
   //观众观看 演员等待
   String voice; //表演的节目
   boolean flag = true;
   //表演
   public synchronized void play(String voice){
       if (!flag){
           try{
               this.wait();
          }catch(InterruptedException e){
               e.printStackTrace();
          }
      }
       System.out.println("演员表演了:" + voice);
       //通知观众观看
       this.notifyAll(); //通知唤醒
       this.voice = voice;
       this.flag = !this.flag;
  }
   //观看
   public synchronized void watch(){
       if (flag){
           try{
               this.wait();
          }catch (InterruptedException e){
               e.printStackTrace();
          }
      }
       System.out.println("观看了:" + voice);
       //通知演员表演
       this.notifyAll();
       this.flag = !this.flag;
  }
}

线程池

  • 含义:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。

  • 思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中;可以避免频繁创建和销毁、实现重复利用,类似生活中的公共交通工具。

  • 好处:

    • 提高响应速度(减少了创建新线程的时间)

    • 降低资源消耗(线程池中的线程可以重复利用,不需要每次都重新创建)

    • 便于线程管理(...)

      • corePoolSize:核心池的大小

      • maximumPoolSize:最大线程数

      • keepAliveTime:线程没有任务时最多保持多长时间后会终止。

线程池的两个类

  • JDK 5.0起提供了线程池相关API:ExecutorService 和 Executors

  • ExecutorService:真正的线程池接口,常见子类ThreadPoolExecutor

    • void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable。

    • <T>Future<T>submit(Callable<T>task):执行任务,有返回值,一般用来执行callable。

    • void shutdown():关闭连接池

  • Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池。

package com.kuang.advanced;
//测试线程池
public class TestPool{
   public static void mian(String[] args){
       //1.创建服务、创建线程池
       //newFixedThreadPool 参数为线程池大小
       ExecutorService service = Executors.newFixedThreadPool(10);
       //执行Runnable接口的实现类
       service.execute(new MyThread());
       service.execute(new MyThread());
       service.execute(new MyThread());
       service.execute(new MyThread());
       
       //3.关闭连接
       service.shutdown();
  }
}

class MyThread implements Runnable{
   @Override
   public void run(){
       for (int i=0; i<10; i++){
           System.out.println(Thread.currentThread().getName() + i);
      }
  }
}

<font color=green>各类线程定义与启动方式一览</font>

package com.kuang.advanced;

implements java.util.concurrent.Callable;
implements java.util.concurrent.FutureTask;

//回顾总结线程的创建
public class ThreadNew{
   public static void main(String[] args){
       new MyThread1().start();
       new Thread(new MyThread2()).start();
       //Callable接口启动方法非常多,<Integer>是泛型约束,Integer是约束类型的一种。
       FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyThread3());
       new Thread(futureTask).start();
       //捕获异常,获得futureTask的返回值
       try{
           Integer integer = futureTask.get();
           System.out.println();
      }catch (InterruptedException e){
           e.printStackTrace();
      }catch (ExecutionException e){
           e.printStackTrace();
      }
  }
}

//1.继承Thread类
class MyThread1 extends Thread{
   @Override
   public void run(){
       System.out.println("MyThread1");
  }
}

//2.实现Runnable接口
class MyThread2 implements Runnable{
   @Override
   public void run(){
       System.out.println("MyThread2");
  }
}

//3.实线Callable接口
class MyThread3 implements Callable<Integer>{
   @Override
   public Integer call() throws Exception{
       System.out.println("MyThread3");
       return 100;
  }
}

posted on 2021-11-17 19:38  愿将过往均储藏  阅读(54)  评论(0)    收藏  举报

导航