线程池的创建及使用

线程池的三种创建方式

  1. 创建固定大小的线程池
ExecutorService pool = Executors.newFixedThreadPool(2);
Runnable task = new Runnable() {
    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
        }
    }
};
pool.execute(task);
pool.execute(task);
pool.execute(task);//线程池的带下只有两个   现在这个任务在其等待队列中排队等候
  1. 创建可变大小的线程池
ExecutorService pool = Executors.newCachedThreadPool();
Runnable task = new Runnable() {
    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
        }
    }
};
pool.execute(task);
pool.execute(task);
pool.execute(task);
  1. 创建独立任务的线程池
ExecutorService pool = Executors.newSingleThreadExecutor();
Runnable task = new Runnable() {
    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
        }
    }
};
pool.execute(task);
pool.execute(task);
pool.execute(task);
线程池的创建 用到的具体函数和方法
创建固定大小容量的线程池 ExecutorService pool = Executors.newFixedThreadpool()
创建可变大小的线程池 ExecutorService pool = Executors.newCachedThreadPool()
创建独立任务的线程池 ExecutorServce pool = Executors.newSingleThreadExecutor()

你可能感兴趣的:(线程池的创建及使用)