因为每一个线程的启动和结束都是比较消耗时间和占用资源的。如果在系统中用到了很多的线程,大量的启动和结束动作,会导致系统的性能很卡,响应变慢。

线程池的模式很像生产者消费者模式,消费的对象是一个一个的能够运行的任务。

二、思想:

1、准备一个任务容器

2、一次性启动10个消费者线程

3、刚开始任务容器是空的,所以线程都wait在上面

4、直到一个外部线程往这个任务容器中扔一个“任务”,就会有一个消费者线程被唤醒notify。

5、这个消费者线程取出任务,并且执行这个任务,执行完毕后,继承等待下一次任务的到来

6、短时间内,有较多的任务加入,那么就会有多个线程被唤醒,去执行这些任务。

在整个过程中,都不需要创建新的线程,而是循环使用这些已存在的线程。

线程1,运行完毕后,不结束线程,回头又来找新的任务。一、线程池

建立线程池的代码:

package ThreadPool;
import java.util.LinkedList;
public class ThreadPool{
    //线程池大小
    int threadPoolSize;
    //任务容器
    LinkedList<Runnable> tasks=new LinkedList<Runnable>();
    //试图消费任务的线程
    public ThreadPool(){
        threadPoolSize=10;
        //启动10个任务消费者线程
        synchronized(tasks){
            for(int i=0;i<threadPoolSize;i++){
                new TaskConsumeThread("任务消费者线程"+i).start();
            }
        }
    }
    public void add(Runnable r){
        synchronized(tasks){
            tasks.add(r);
            //唤醒等待的任务消费者线程
            tasks.notifyAll();
        }
    }
    
    class TaskConsumeThread extends Thread{
        public TaskConsumeThread(String name){
            super(name);
        }
        Runnable task;
        
        public void run(){
            System.out.println("启动:"+this.getName());
            while(true){
                synchronized(tasks){
                    while(tasks.isEmpty()){
                        try{
                                tasks.wait();
                        }catch(Exception e){
                            e.printStackTrace();
                        }
                    }
                    task=tasks.removeLast();
                    tasks.notifyAll();
                }
                System.out.println(this.getName()+"获取到任务,并进行");
                task.run();
            }
        }
    }
}
View Code

相关文章:

  • 2021-08-23
  • 2021-06-12
  • 2022-12-23
  • 2022-12-23
  • 2021-10-30
  • 2022-12-23
  • 2021-07-04
  • 2021-11-14
猜你喜欢
  • 2021-11-30
  • 2022-12-23
  • 2021-08-14
  • 2021-05-24
  • 2021-07-24
相关资源
相似解决方案