JAVA JUC 线程池
线程池提供了一个线程队列,队列中保存着所有等待状态的线程.避免了频繁的创建和销毁线程池,提高了响应速度
java.util.concurrent.Executor: 负责线程池的使用和调度的根接口
|----ExecutorService 子接口:线程池的主要接口
|----ThredPoolExecutor 线程池的实现类
|----ScheduledExecutorService 子接口:负责线程的调度
|----ScheduledThreadPoolExecutor 继承了ThreadPoolExecutor,实现了ScheduledExecutorService
java.util.concurrent.Executors: 线程池的工具类
方法:
ExecutorService newFixedThreadPool() : 创建固定大小的线程池
ExecutorService newCachedThreadPool() : 缓存线程池,线程池的大小根据需要自动调整
ExecutorService newSingleThreadExecutor() : 创建线程池,只包含一个线程
ScheduledExecutorService newScheduledThreadPool() : 创建固定大小的线程池,可以延时或者定时执行
线程池应用示例
package com.LearnJava.JUC; import javax.swing.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; class Demo2 implements Runnable{ private int num; private ReentrantLock lock = new ReentrantLock(); public int Sum(int num){ int sum = 0; for(int i=0;i<num;i++){ sum+=i; } return sum; } @Override public void run() { while (num<100){ int f = 0; lock.lock(); f=num++; lock.unlock(); System.out.println(Thread.currentThread().getName()+" "+"sum "+f+" "+Sum(f)); //System.out.println("sum "+i+" "+Sum(i)); } } } public class threadPoolTest { public static void main(String[] args) { ExecutorService pool = Executors.newFixedThreadPool(5); Demo2 d2 = new Demo2(); for(int i=0;i<10;i++){ pool.submit(d2); } pool.shutdown(); } }
scheduledThreadPool示例
public static void main(String[] args) { ScheduledExecutorService pool = Executors.newScheduledThreadPool(5); for(int i=0;i<10;i++){ pool.schedule(new Runnable() { @Override public void run() { int s = new Random().nextInt(100); System.out.println(Thread.currentThread().getName()+" "+s); } },3, TimeUnit.SECONDS); } pool.shutdown(); } }