线程池的运用 java

使用线程池插入数据,下面的testThreadPool类

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

public class testThreadPool {
    //创建一个线程池 初始化3个线程
    public static ExecutorService pool = Executors.newFixedThreadPool(3);
    
    //阻塞队列
    public static BlockingQueue queue = new LinkedBlockingDeque<>();
    
    public static void main(String[] args) {
        TestBlockingQueue testq = new TestBlockingQueue(queue);
        for(int i = 0;i < 10;i++) {
            testq.pushData(i);
            pool.execute(testq);
        }
    }

} 
  

TestBlockingQueue的代码如下

import java.util.concurrent.BlockingQueue;

public class TestBlockingQueue implements Runnable {
    //阻塞队列
    private BlockingQueue queue;
    
    public TestBlockingQueue(BlockingQueue queue){
        this.queue = queue;
    }
    
    public TestBlockingQueue(){}
    /**
     * 添加数据
     * @param dataMap   数据
     */
    public void pushData(Object obj) {
        this.queue.offer(obj);
    }
    
    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName()+"-->"+this.queue.poll());
            //线程睡眠2秒测试
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
} 
  

你可能感兴趣的:(学习笔记)