Java中的线程
约 701 字大约 2 分钟
线程并发
2020-03-02
线程和进程
线程的创建方式
继承Thread类创建线程
public class MyThread extends Thread{//继承Thread类
public void run(){
//重写run方法
}
}
public class Main {
public static void main(String[] args){
new MyThread().start();//创建并启动线程
}
}
实现Runnable接口
使用Callable和Future创建线程
线程的生命周期
Java 线程在运行的生命周期中的指定时刻只可能处于下面 6 种不同状态的其中一个状态(图源《Java 并发编程艺术》4.1.4 节)。 线程在生命周期中并不是固定处于某一个状态而是随着代码的执行在不同状态之间切换。Java 线程状态变迁如下图所示(图源《Java 并发编程艺术》4.1.4 节):
守护线程
https://www.cnblogs.com/yongdaimi/p/12010006.html
其他
ThreadPoolExecutor 源码解析
- 参数解析
1.corePoolSize 核心线程数(the number of threads to keep in the pool),线程池在创建之后,默认情况下线程池中并没有任何一个线程,而是等有任务到来才去创建线程去执行对应的任务。当线程池中的线程数达到corePoolSize后,新来的任务将会被添加到缓存队列中。 ps:int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors(); 2.maximumPoolSize 最大线程数(the maximum number of threads to allow in the pool),表示线程池中允许创建的最大线程数。当线程池中的线程数等于 corePoolSize 并且 workQueue 已满,这时就要看当前线程数是否大于 maximumPoolSize,如果小于maximumPoolSize 定义的值,则会继续创建线程去执行任务, 否则将会调用去相应的任务拒绝策略来拒绝这个任务。
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
3.keepAliveTime 4.TimeUnit unit