线程重复运行问题
一个线程的start,只能start一次,再次调用start方法就会抛出异常。
内部实现这个的原理是:
线程对象内部有一个字段,初始值是0

调用一次start方法之后,这个值会被置成其他值(并没有找到在哪里置其他值)
如果重复掉用这个start,会判断这个值如果不是0了就抛出异常,所以导致一个线程只能被start一次。

场景
使用线程A实现了功能A,这个功能A需要被多次调用,但是这个线程A又不能多次start,导致无法多次调用这个功能A。
于是乎只能多次new线程A的对象,这种虽然可行,但是功能A跑一次就需要一个新的线程A对象,这越积越多,不见得之前用完的线程A对象会被及时回收,这就不可靠。
线程池
线程池的使用
- newSingleThreadExecutor()
线程池里只有一个线程在运行,所以结果是thread1运行完了,在运行thread2,2运行完了在运行3,3运行完了,在运行4
public class Main {
public static void main(String[] args){
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(new MyRun("thread1"));
executor.submit(new MyRun("thread2"));
executor.submit(new MyRun("thread3"));
executor.submit(new MyRun("thread4"));
executor.shutdown();
}
}
class MyRun implements Runnable{
private String name;
public MyRun(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println(this.name+"---"+i);
}
}
}
- newFixedThreadPool(2);
指定同时运行的线程的数量为2,效果就是同时运行线程1和2,然后比如1先运行完了,把3加进来,就变成了同时运行2和3。
public class Main {
public static void main(String[] args){
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(new MyRun("thread1"));
executor.submit(new MyRun("thread2"));
executor.submit(new MyRun("thread3"));
executor.submit(new MyRun("thread4"));
executor.shutdown();
}
}
class MyRun implements Runnable{
private String name;
public MyRun(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println(this.name+"---"+i);
}
}
}
- newCachedThreadPool();
具体运行几个线程有系统自动判断,线程多了自动回收,线程少了自己创建。
public class Main {
public static void main(String[] args){
ExecutorService executor = Executors.newCachedThreadPool();
executor.submit(new MyRun("thread1"));
executor.submit(new MyRun("thread2"));
executor.submit(new MyRun("thread3"));
executor.submit(new MyRun("thread4"));
executor.shutdown();
}
}
class MyRun implements Runnable{
private String name;
public MyRun(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println(this.name+"---"+i);
}
}
}
- newScheduledThreadPool(2);
延迟时间执行,参数指定为同时运行的线程的数量。如果加入了多个runnable,只会在开始运行的时候有延迟,并不会没有个runnable都有延迟。需要注意返回的对象有不同,是ScheduledExecutorService。
public class Main {
public static void main(String[] args){
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
executor.schedule(new MyRun("thread1"),3000, TimeUnit.MILLISECONDS);
executor.schedule(new MyRun("thread2"),3000, TimeUnit.MILLISECONDS);
executor.schedule(new MyRun("thread3"),3000, TimeUnit.MILLISECONDS);
executor.shutdown();
}
}
class MyRun implements Runnable{
private String name;
public MyRun(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(this.name+"---"+i);
}
}
}
线程池的原理
线程的重复的创建是需要耗费很多的性能的,线程池对这个进行管理,线程池可以重复使用线程,所以可以节约性能。
这里涉及到一个问题,前面有介绍过,一个线程是不可能重复start,换句话说一个线程执行完了以后就不能再被执行了,那么这个线程池是这么重复利用的呢?
其实最底层的原理也很简单,就是线程池想要重复运行的线程根本就没有运行完过,那些线程的run方法其实是一个死循环,如果有runnable过来了,就运行runnable的run,如果没有,就是while(true)的死循环,所以这个线程才可以达到重复使用的目的。
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
//看这里
while (task != null || (task = getTask()) != null) {
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
Throwable thrown = null;
try {
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
线程池的流程
一些概念
这个是线程池的构造方法,上面的几个不同的线程池newScheduledThreadPool、newCachedThreadPool等等其实都是调用的这个构造方法,只不过传递进去的参数不一样,所以会有不一样的效果。
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
- corePoolSize:核心线程数,就是之前的Executors.newScheduledThreadPool(2)的参数2。核心线程是不会被销毁的,就是一直while(true)。
- 非核心线程:这个是当核心线程不够用的时候,会创建非核心线程来执行runnable任务,等到执行完了,空闲了一段时间后就会被销毁。
- maximumPoolSize:最大线程数,核心线程数+非核心线程数<=最大线程数。
- keepAliveTime:非核心线程空闲多久才会被销毁。
- TimeUnit:keepAliveTime的单位,秒啊,分啊什么的。
- workQueue:存放runnable任务的队列,比如newScheduledThreadPool(2)核心线程数是2,但是呢代码submit了4个runnable,这样子一下子只能跑2个runnable,多出来的2个就会被放到这个queue里面,等待前两个runnable运行完了在被运行。
- handler:runnable如果太多了,核心线程都在运行,queue里面塞满了,连非核心线程也全部跑满了,就得有一定的拒绝策略,不能让runnable一直过来。

流程
首先runnable不断的过来,然后放到queue里面,核心线程不断的从queue里面把runnable取出来运行,形成了一个生产者消费者的模式。
如果runnable进来的速度比核心线程池里面的核心线程消费的速度快的话,多出来的就会存在queue里面,但是这个queue也是有大小限制的。
如果这个queue都塞满了,就得增加消费者的消费速度,怎么办呢?就是创建非核心线程,非核心线程也去消费queue里面的runnable,以此来提升消费者的速度。但是非核心线程也是有数量限制的,核心线程数+非核心线程数<=maximumPoolSize。
如果runnable不多了,非核心线程就会闲置下来,当闲置了keepAliveTime这么长时间以后还没有被使用的话,就会被销毁掉。当然核心线程是不会被销毁的。
如果runnable超级超级多,就算是非核心线程数也跑满了,队列还是放不下那么多的runnable,就只能拒绝了,有一些不同的拒绝策略。
饱和策略
- CallerRunsPolicy:直接用调用者所在线程来运行任务。
- DiscardOldestPolicy:丢弃队列里最前面的一个任务,把当前的任务放到最前面。
- DiscardPolicy:不把runnable放到queue里面,直接丢掉。
- AbortPolicy:直接抛出异常。
queue
- ArrayBlockingQueue:基于数组、有界,按 FIFO(先进先出)原则对元素进行排序
- LinkedBlockingQueue:基于链表,按FIFO (先进先出) 排序元素
吞吐量通常要高于 ArrayBlockingQueue
Executors.newFixedThreadPool() 使用了这个队列 - SynchronousQueue:不存储元素的阻塞队列
每个插入操作必须等到另一个线程调用移除操作,否则插入操作一直处于阻塞状态
吞吐量通常要高于 LinkedBlockingQueue
Executors.newCachedThreadPool使用了这个队列 - PriorityBlockingQueue:具有优先级的、无限阻塞队列