首页 > 技术专区 > Java > 线程池 并发队列 ThreadPoolExecutor原理解析 屏幕太窄?试试伸展一下吧 >

线程池 并发队列 ThreadPoolExecutor原理解析

1. 并发队列

image.png

入队:

非阻塞队列:当队列中满了时候,放入数据,数据丢失

阻塞队列:当队列满了的时候,进行等待,什么时候队列中有出队的数据,那么第11个再放进去。

出队:

非阻塞队列:如果现在队列中没有元素,取数据,得到的是null

阻塞队列:等待,什么时候放进去,再取出来。


线程池----阻塞队列

2. 线程池底层原理

image.png

3. 线程池的分类

可缓存 newCachedThreadPool()

package com.liqinglin.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPool {
    public static void main(String[] args) {
        ExecutorService es = Executors.newCachedThreadPool();
        for(int i = 0; i < 100; i++){
            es.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                }
            });
        }
        es.shutdown();
    }
}

定长 newFixedThreadPool()

package com.liqinglin.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPool {
    public static void main(String[] args) {
        ExecutorService es = Executors.newFixedThreadPool(3);
        for(int i = 0; i < 100; i++){
            es.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                }
            });
        }
        es.shutdown();
    }
}

定时 newScheduledThreadPool()

package com.liqinglin.test;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ThreadPool {
    public static void main(String[] args) {
        ScheduledExecutorService ses = Executors.newScheduledThreadPool(3);
        for(int i = 0; i < 100; i++){
            ses.schedule(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                }
            },3, TimeUnit.SECONDS);
        }
        ses.shutdown();
    }
}

单例 newSingleThreadExecutor()

package com.liqinglin.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPool {
    public static void main(String[] args) {
        ExecutorService es = Executors.newSingleThreadExecutor();
        for(int i = 0; i < 100; i++){
            es.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                }
            });
        }
        es.shutdown();
    }
}