1. 线程通信
什么是线程通信?
- 当多个线程共同操作共享的资源时,线程间通过某种方式互相告知自己的状态,以相互协调,并避免无效的资源争夺。
线程通信的常见模型(生产者与消费者模型)
- 生产者线程负责生产数据
- 消费者线程负责消费生产者生产的数据。
- 注意:生产者生产完数据应该等待自己,通知消费者消费;消费者消费完数据也应该等待自己,再通知生产者生产!
线程通信的模型
-
3个生产者线程,负责生产包子,每个线程每次只能生产1个包子放在桌子上
-
2个消费者线程负责吃包子,每人每次只能从桌子上拿1个包子吃。
Object类的等待和唤醒方法:
注意:
- 上述方法应该使用当前同步锁对象进行调用。
代码演示
public class Desk {
// 包子集合
private List<String> list = new ArrayList<>();
// 做包子
public synchronized void put() {
try {
// 当前线程名称(生产者:厨师1,厨师2,厨师3)
String name = Thread.currentThread().getName();
// 每个线程每次只能生产1个包子放在桌子
if(list.size() == 0){ // 桌上没包子
list.add(name + "做的肉包子");
System.out.println(name + "做了一个肉包子~~");
Thread.sleep(2000);
this.notifyAll();
this.wait();
}else{ // 桌上有包子
// 有包子了,不做了。
// 唤醒别人, 等待自己
this.notifyAll();
this.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 吃包子
public synchronized void get() {
try {
// 当前线程名称(消费者:吃货1,吃货2)
String name = Thread.currentThread().getName();
if(list.size() == 1){ // 有包子吃
System.out.println(name + "吃了" + list.get(0));
list.clear();
Thread.sleep(1000);
// 唤醒别人, 等待自己
this.notifyAll();
this.wait();
}else{ // 没包子吃
// 唤醒别人, 等待自己
this.notifyAll();
this.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class ThreadTest {
public static void main(String[] args) {
// 桌子对象
Desk desk = new Desk();
// 创建3个生产者线程,2个消费者线程
new Thread(() -> {
while(true){
desk.put();
}
}, "厨师1").start();
new Thread(() -> {
while(true){
desk.put();
}
}, "厨师2").start();
new Thread(() -> {
while(true){
desk.put();
}
}, "厨师3").start();
new Thread(() -> {
while(true){
desk.get();
}
}, "吃货1").start();
new Thread(() -> {
while(true){
desk.get();
}
}, "吃货2").start();
}
}
执行结果
2. 线程池
1. 认识线程池
什么是线程池?
- 线程池就是一个可以复用线程的技术。
不使用线程池的问题
- 用户每发起一个请求,后台就需要创建一个新线程来处理,下次新任务来了肯定又要创建新线程处理的, 而创建新线程的开销是很大的,并且请求过多时,肯定会产生大量的线程出来,这样会严重影响系统的性能。
线程池的工作原理
2. 如何创建线程池
谁代表线程池?
- JDK 5.0起提供了代表线程池的接口:ExecutorService。
如何得到线程池对象?
- 方式一:使用ExecutorService的实现类ThreadPoolExecutor自创建一个线程池对象。
- 方式二:使用Executors(线程池的工具类)调用方法返回不同特点的线程池对象。
ThreadPoolExecutor构造器
public ThreadPoolExecutor(int corePoolSize // 正式工:3
, int maximumPoolSize // 最大员工数:5, 临时工:2
, long keepAliveTime // 临时工空闲多久被开除
, TimeUnit unit
, BlockingQueue<Runnable> workQueue // 客人排队的地方
, ThreadFactory threadFactory // 负责招聘员工的(hr)
, RejectedExecutionHandler handler) // 忙不过来咋办
- 参数一:corePoolSize : 指定线程池的核心线程的数量。
- 参数二:maximumPoolSize:指定线程池的最大线程数量。
- 参数三:keepAliveTime :指定临时线程的存活时间。
- 参数四:unit:指定临时线程存活的时间单位(秒、分、时、天)
- 参数五:workQueue:指定线程池的任务队列。
- 参数六:threadFactory:指定线程池的线程工厂。
- 参数七:handler:指定线程池的任务拒绝策略(线程都在忙,任务队列也满了的时候,新任务来了该怎么处理
线程池的注意事项
1、临时线程什么时候创建?
- 新任务提交时发现核心线程都在忙,任务队列也满了,并且还可以创建临时线程,此时才会创建临时线程。
2、什么时候会开始拒绝新任务?
- 核心线程和临时线程都在忙,任务队列也满了,新的任务过来的时候才会开始拒绝任务。
3. 线程池处理Runnable任务
ExecutorService的常用方法
新任务拒绝策略
代码演示
public class MyRunnable implements Runnable{
@Override
public void run() {
// 任务是干啥的?
System.out.println(Thread.currentThread().getName() + " ==> 输出666~~");
try {
Thread.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class ThreadPoolTest1 {
public static void main(String[] args) {
ExecutorService pool = new ThreadPoolExecutor(3,
5,
8,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(4),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略:由主线程负责调用任务的run()方法从而绕过线程池直接执行
/*
临时线程什么时候创建?
1.核心线程都在忙 (核心线程:3)
2.任务队列满了 (任务队列容量:4)
什么时候开始拒绝新任务?
1.核心线程在忙 (核心线程:3)
2.临时线程在忙 (临时线程:线程池最大线程数 - 核心线程数;5 - 3 = 2)
3.任务队列满了 (任务队列容量:4)
*/
Runnable target = new MyRunnable();
pool.execute(target); // 线程池会自动创建一个新线程,自动处理这个任务,自动执行的!
pool.execute(target); // 线程池会自动创建一个新线程,自动处理这个任务,自动执行的!
pool.execute(target); // 线程池会自动创建一个新线程,自动处理这个任务,自动执行的!
pool.execute(target);
pool.execute(target);
pool.execute(target);
pool.execute(target);
// 到了临时线程的创建时机了
pool.execute(target);
pool.execute(target);
// 到了新任务的拒绝时机了!
pool.execute(target);
}
}
4. 线程池处理Callable任务
ExecutorService的常用方法
代码演示
public class MyCallable implements Callable<String> {
private int n;
public MyCallable(int n) {
this.n = n;
}
@Override
public String call() throws Exception {
// 描述线程的任务,返回线程执行返回后的结果。
// 需求:求1-n的和返回。
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
return Thread.currentThread().getName() + "求出了1-" + n + "的和是:" + sum;
}
}
/**
* 目标:掌握线程池的创建。
*/
public class ThreadPoolTest2 {
public static void main(String[] args) throws Exception {
ExecutorService pool = new ThreadPoolExecutor(3,
5,
8,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(4),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy());
// 2、使用线程处理Callable任务。
Future<String> f1 = pool.submit(new MyCallable(100));
Future<String> f2 = pool.submit(new MyCallable(200));
Future<String> f3 = pool.submit(new MyCallable(300));
Future<String> f4 = pool.submit(new MyCallable(400));
System.out.println(f1.get());
System.out.println(f2.get());
System.out.println(f3.get());
System.out.println(f4.get());
}
}
5. Executors工具类实现线程池
Executors
-
是一个线程池的工具类,提供了很多静态方法用于返回不同特点的线程池对象。
-
注意 :这些方法的底层,都是通过线程池的实现类ThreadPoolExecutor创建的线程池对象。
代码演示
public class MyCallable implements Callable<String> {
private int n;
public MyCallable(int n) {
this.n = n;
}
@Override
public String call() throws Exception {
// 描述线程的任务,返回线程执行返回后的结果。
// 需求:求1-n的和返回。
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
return Thread.currentThread().getName() + "求出了1-" + n + "的和是:" + sum;
}
}
/**
* 目标:掌握线程池的创建。
*/
public class ThreadPoolTest3 {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(9);
// 核心线程数量到底配置多少呢???
// 计算密集型的任务:核心线程数量 = CPU的核数 + 1
// IO密集型的任务:核心线程数量 = CPU核数 * 2
// 2、使用线程处理Callable任务。
Future<String> f1 = pool.submit(new MyCallable(100));
Future<String> f2 = pool.submit(new MyCallable(200));
Future<String> f3 = pool.submit(new MyCallable(300));
Future<String> f4 = pool.submit(new MyCallable(400));
System.out.println(f1.get());
System.out.println(f2.get());
System.out.println(f3.get());
System.out.println(f4.get());
}
}
Executors使用可能存在的陷阱
- 大型并发系统环境中使用Executors如果不注意可能会出现系统风险。
3. 其它细节知识:并发、并行
进程
- 正在运行的程序(软件)就是一个独立的进程。
- 线程是属于进程的,一个进程中可以同时运行很多个线程。
- 进程中的多个线程其实是并发和并行执行的。
并发的含义
- 进程中的线程是由CPU负责调度执行的,但CPU能同时处理线程的数量有限,为了保证全部线程都能往前执行,CPU会轮询为系统的每个线程服务,由于CPU切换的速度很快,给我们的感觉这些线程在同时执行,这就是并发
并行的理解
- 在同一个时刻上,同时有多个线程在被CPU调度执行。
简单说说多线程是怎么执行的?
- 并发:CPU分时轮询的执行线程。
- 并行:同一个时刻同时在执行。
4. 其它细节知识:线程的生命周期
人的生命周期(各种状态)
线程的生命周期
- 也就是线程从生到死的过程中,经历的各种状态及状态转换。
- 理解线程这些状态有利于提升并发编程的理解能力
Java线程的状态
- Java总共定义了6种状态
- 6种状态都定义在Thread类的内部枚举类中。
public class Thread{
public enum State {
NEW
,RUNNABLE
,BLOCKED
,WAITING
,TIMED_WAITING
,TERMINATED;
}
}