重点:
1.可以使用wait和notify两种方法
2.使用Lock锁对象
3.Callable接口将用于实现多线程
4.将使用线程池完成多线程
第一章等待唤醒机制
1.等待唤醒案例分析(线程之间的通信)
要求:线程生产,线程消费,不能连续生产,不能连续消费 -> 等待唤醒机制(生产者、消费者)(线程之间的通信)
wait和notify方法需要对锁对象进行调用,因此需要在同步代码块中使用,必须是同一锁对象


/*
count和flag可以定义为包装类
但要记得手动赋值count和flag
否则,在本案中,很容易出现空指针异常
*/
public class BaoZiPu {
//代表包子的count
private int count;
///代表是否有包子flag
private boolean flag;
public BaoZiPu() {
}
public BaoZiPu(int count, boolean flag) {
this.count = count;
this.flag = flag;
}
/*
getCount 将其转化为消费包子的方法
count直接输出
*/
public void getCount() {
System.out.println("消费了...第"+count+"个包子";
}
/*
setCount 将其改造成生产包子
count++
*/
public void setCount() {
count++;
System.out.println("生产了...第"+count+"个包子";
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
public class Product implements Runnable{
private BaoZiPu baoZiPu;
public Product(BaoZiPu baoZiPu) {
this.baoZiPu = baoZiPu;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (baoZiPu){
//1.判断flag是否为true,假如是true,证明有包子,等待生产线
if (baoZiPu.isFlag()==true){
try {
baoZiPu.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//2.如果flag是false,证明没有包子,开始生产
baoZiPu.setCount();
//3.改变flag状态,为true,证明生产完成,有包子
baoZiPu.setFlag(true);
//4.唤醒消费线程
baoZiPu.notify();
}
}
}
}
public class Consumer implements Runnable{
private BaoZiPu baoZiPu;
public Consumer(BaoZiPu baoZiPu) {
this.baoZiPu = baoZiPu;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (baoZiPu){
//1.判断flag是否为false,假如是false,证明没有包子,等待消费线程
if (baoZiPu.isFlag()==false){
try {
baoZiPu.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//2.如果flag是true,证明有包子,开始消费
baoZiPu.getCount();
//3.为false改变flag状态,证明消费已经结束,没有 有包子了
baoZiPu.setFlag(false);
/4.唤醒生产线程
baoZiPu.notify();
}
}
}
}
public class Test01 {
public static void main(String[] args) {
BaoZiPu baoZiPu = new BaoZiPu();
Product product = new Product(baoZiPu);
Consumer consumer = new Consumer(baoZiPu);
Thread t1 = new Thread(product);
Thread t2 = new Thread(consumer);
t1.start();
t2.start();
}
}

结论:在这个例子中,我们应该考虑同步和相互排斥的问题:我们应该实现一个消费者的生产,只有一个生产者和消费者,这应该考虑:两个线程访问相同的资源,我们使用同步代码锁定;我们还需要考虑生产和消费者的顺序,我们使用wait和notify。
我们使用同步代码在消费者和生产者中重写run方法,我们使用对象实例作为mutex互斥锁,使用变量来判断是生产还是消费,如果判断成功,在等待队列中,否则操作,然后随机唤醒等待队列的过程。
3.同步等待唤醒案例/*
可以将count和flag定义为包装类
但要记得手动赋值count和flag
否则,在本案中,很容易出现空指针异常
*/
public class BaoZiPu {
///代表包子的count
private int count;
///代表是否有包子flag
private boolean flag;
public BaoZiPu() {
}
public BaoZiPu(int count, boolean flag) {
this.count = count;
this.flag = flag;
}
/*
getCount 将其转化为消费包子的方法
直接输出count
*/
public synchronized void getCount() {
//1.判断flag是否为false,如果是false,证明没有包子,等待消费线程
if (this.flag == false) {
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//2.如果flag是true,证明有包子,开始消费
System.out.println("消费了...第" + count + "个包子";
//3.为false改变flag状态,证明消费已经结束,没 有包子了
this.flag = false;
/4.唤醒生产线程
this.notify();
}
/*
setCount 将其改造成生产包子
count++
*/
public synchronized void setCount() {
//1.判断flag是否是true,如果是true,证明有包子,等待生产线
if (this.flag == true) {
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//2.如果flag是false,证明没有包子,开始生产
count++;
System.out.println("生产了...第" + count + "个包子";
//3.为true改变flag状态,证明生产已经完成,有包子了
this.flag = true;
//4.唤醒消费线程
this.notify();
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
public class Product implements Runnable{
private BaoZiPu baoZiPu;
public Product(BaoZiPu baoZiPu) {
this.baoZiPu = baoZiPu;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
baoZiPu.setCount();
}
}
}
public class Consumer implements Runnable{
private BaoZiPu baoZiPu;
public Consumer(BaoZiPu baoZiPu) {
this.baoZiPu = baoZiPu;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
baoZiPu.getCount();
}
}
}
public class Test01 {
public static void main(String[] args) {
BaoZiPu baoZiPu = new BaoZiPu();
Product product = new Product(baoZiPu);
Consumer consumer = new Consumer(baoZiPu);
Thread t1 = new Thread(product);
Thread t2 = new Thread(consumer);
t1.start();
t2.start();
}
}
在上述代码中,我们将同步代码放入baoziPu中实现。在这里,由于使用wait和notify实现,我们必须添加关键字。如果不添加synchronized,则会报告异常,因为它是在synchronized方法中调用的,以识别多线程,无法实现wait和notify的功能。
第二章,多等待,多唤醒。 1.解决多生产多消费问题(if改为while,notify改为notifyall)public class Test01 {
public static void main(String[] args) {
BaoZiPu baoZiPu = new BaoZiPu();
Product product = new Product(baoZiPu);
Consumer consumer = new Consumer(baoZiPu);
new Thread(product).start();
new Thread(product).start();
new Thread(product).start();
new Thread(consumer).start();
new Thread(consumer).start();
new Thread(consumer).start();
}
}
/*
count和flag可以定义为包装类
但要记得手动赋值count和flag
否则,在本案中,很容易出现空指针异常
*/
public class BaoZiPu {
///代表包子的count
private int count;
///代表是否有包子flag
private boolean flag;
public BaoZiPu() {
}
public BaoZiPu(int count, boolean flag) {
this.count = count;
this.flag = flag;
}
/*
getCount 将其转化为消费包子的方法
count直接输出
*/
public synchronized void getCount() {
//1.判断flag是否为false,如果是false,证明没有包子,等待消费线程
while (this.flag == false) {
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//2.如果flag是true,证明有包子,开始消费
System.out.println("消费了...第" + count + "个包子");
//3.为false改变flag状态,证明消费已经结束,没 有包子了
this.flag = false;
//4.唤醒所有等待线程
this.notifyAll();
}
/*
setCount 将其改造成生产包子
count++
*/
public synchronized void setCount() {
//1.判断flag是否是true,如果是true,证明有包子,等待生产线
while (this.flag == true) {
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//2.如果flag是false,证明没有包子,开始生产
count++;
System.out.println("生产了...第" + count + "个包子";
//3.为true改变flag状态,证明生产已经完成,有包子了
this.flag = true;
//4.唤醒所有等待线程
this.notifyAll();
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
public class Product implements Runnable{
private BaoZiPu baoZiPu;
public Product(BaoZiPu baoZiPu) {
this.baoZiPu = baoZiPu;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
baoZiPu.setCount();
}
}
}
public class Consumer implements Runnable{
private BaoZiPu baoZiPu;
public Consumer(BaoZiPu baoZiPu) {
this.baoZiPu = baoZiPu;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
baoZiPu.getCount();
}
}
}
总结:
这是什么:这是一个多等待多执行的例子,
与第一个不同的是,消费者或生产者可以等待队列
解决方案:if->while,notify->notifyAll,原因:1、将if改为while,如果状态在唤醒后发生变化,在while之后可以跳出这个循环,2、为什么要notifyAll?这是因为notify是随机唤醒的。如果唤醒导致多个生产者被阻塞,它将被锁定。3、这两个需要一起使用才能达到效果。
第三章.Lock锁 1.介绍Lock对象和基本使用1.概述:Lock是一个接口,需要使用它的实现类去实例化对象
2.实现类:ReentrantLock
3.方法:
lock() 获取锁
unlock() 释放锁
4.原理:原理有些复杂,类似于信号量,会计数实现,不会深入讨论。简单来说:每次 lock() 使 state 加 1,每次 unlock() 使 state 减 1。只有 state 只有在归零时,锁才能真正释放并唤醒后续线程。
如:
发现 state == 0(空闲)。
通过 CAS 将 state 从 0 改为 1。
记录当前线程为锁的持有人。
线程进入临界区执行 ticket 操作。
public class MyTicket implements Runnable {
//定义100张票
int ticket = 100;
////创建Lock对象
Lock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
try {
Thread.sleep(100L);
//获取锁
lock.lock();
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + "买了第" + ticket + "张票");
ticket--;
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}finally {
//释放锁
lock.unlock();
}
}
}
}
public class Test01 {
public static void main(String[] args) {
MyTicket myTicket = new MyTicket();
Thread t1 = new Thread(myTicket, "赵四");
Thread t2 = new Thread(myTicket, "刘能");
Thread t3 = new Thread(myTicket, "广坤");
t1.start();
t2.start();
t3.start();
}
}
第四章.Callable接口_实现多线程方式3synchronized:无论是同步代码块还是同步方法,都需要在一对{}结束后释放锁对象 Lock:需要同步的代码由两种方法控制,更加灵活
1.概述:Callable<V>类似Runnnable的界面
2.方法:
V call() -> 设置线程任务类似于run方法
3.call方法和run方法的区别:
a.相似之处:设置线程任务
b.不同点:
call方法有返回值,有异常可以throws
run方法没有返回值,有异常不能throws
4.<V>
a.<V>叫做泛型
b.泛型:用于指定我们操作的数据类型,<>引用数据类型只能写在中间。如果不写泛型,默认为Object类型数据。
c.在实现Calable接口时,指定什么类型的泛型,重写的call方法返回值是什么类型?
5.获取call方法返回值: FutureTask<V>
a. FutureTask<V> 实现了一个接口: Future <V>
b. FutureTask<V>有一种方法:
V get() -> 获取call方法的返回值
6.问题:为什么一个简单的“带返回值的任务”要绕这么大一圈——首先创建它 Callable,再包成 FutureTask,然后才能交给 Thread 去跑?
核心原因如下:Thread 类只认 Runnable,不认 Callable。
核心原因如下:Thread 类只认 Runnable,不认 Callable。
Thread 构造函数参数只能是 Runnable,而 Runnable.run() 没有返回值,也不能抛出异常检查。如果我们想让线程执行一个接一个地返回 因此,必须使用“包装”手段 Callable 伪装成 Runnable,同时,我们可以在未来的某个时刻得到结果。FutureTask 用来做这个包装:
它实现了 RunnableFuture 接口,而 RunnableFuture 同时继承了 Runnable 和 Future。
所以 FutureTask 本身就可以当作 Runnable 传给 Thread(Thread 看到的是 run() 方法)。
同时又提供了 Future 方法(例如 get(),让调用方阻止等待结果。
你可以把 FutureTask 理解为桥梁:同时连接 Callable(真正的任务逻辑),另一边可以 Thread 提供 run() 入口还可以为调用器提供获取结果的接口。
总而言之:Thread只认可Runable,但Runable没有返回值,因此,设计了一种接口Future获得返回值的方法
Runable接口 Future接口
|-> RunnableFuture 接口 <-|
| (call方法)
实现类Futuretask --------------- Callable
|(传入)
Thread中的方法,因为此时Futuretask可以看作是Ruable子类
Callable 能放进 FutureTask,仅仅是因为 FutureTask 内部定义了一个 Callable 类型的字段,并在结构中保存,没有任何魔法。FutureTask 再通过实现 Runnable,使这个“装有” Callable “任务”可以被接受 Thread 执行时自动调用 call() 并保存结果。FutureTask 再通过实现 Runnable,使这个“装有” Callable “任务”可以被接受 Thread 执行时自动调用 call() 并保存结果。
但这种用法并不多,大部分都是用线程池完成的
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
return 陶哥和金莲...的故事";
}
}
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable myCallable = new MyCallable();
/*
FutureTask(Callable<V> callable)
*/
FutureTask<String> futureTask = new FutureTask<>(myCallable);
////创建Thread对象-> Thread(Runnable target)
Thread t1 = new Thread(futureTask);
t1.start();
////调用get方法获得call方法返回值
System.out.println(futureTask.get());
}
}
第五章。线程池_实现多线程方法4

1.问题:在线程任务之前,您需要创建一个线程对象来执行,并在使用后销毁线程对象。如果有更多的线程任务,您需要经常创建线程对象和销毁线程对象(核心问题),这将消耗内存资源。因此,我们认为线程对象是否可以回收利用,使用时直接取线程对象,使用后返回
1.如何创建线程池对象:工具类-> Executors
2.获取线程池对象:Executors中的静态方法:
static ExecutorService newFixedThreadPool(int nThreads)
a.参数:指定线程池中最多创建的线程对象条数
b.ExecutorService返回值 用于管理线程对象的线程池
3.执行线程任务: ExecutorService中的方法
Future<?> submit(Runnable task) 执行Runnable任务
Future<T> submit(Callable<T> task) 执行Callable任务
4.submit方法的返回值:future接口
用于接收run方法或call方法的返回值,但run方法没有返回值,因此无需Future即可接收,执行call方法需要Future接收
Future中有一种方法:V get() 用于获取call方法的返回值
5. ExecutorService中的方法:
void shutdown() 启动有序关闭,之前提交的任务将被执行,但不接受任何新任务
6. 实现细节
1.创建n个线程线程的线程池
ExecutorService executor = Executors.newSingleThreadExecutor(n);
newsinglethreadexecutor是一种静态方法,ExecutorService返回值
2. 提交 Callable 任务
Future<String> future = executor.submit(new MyCallable());
submit 方法内部(以 AbstractExecutorService 以默认实现为例)会做两件事:
① 将 Callable 包装成 FutureTask
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return new FutureTask<T>(callable);
}
这一步和你之前手动写的一步一样 FutureTask<String> futureTask = new FutureTask<>(myCallable); 完全一样——它产生了一个既实现了的东西 Runnable(可以由线程执行)又实现了 Future(可获得结果)对象。
② 把 FutureTask 交给线程池执行
public Future<?
② 把 FutureTask 交给线程池执行
public Future<?> submit(Runnable task) {
// 实际调用 execute 方法,参数是 Runnable
execute(task);
return future;
}
execute 是 ThreadPoolExecutor 其核心方法:
若未创建工作线程,则创建新的线程(或重用现有的空闲线程)。
将 FutureTask(作为 Runnable)把工作队列放进去。
工作线程将不断地从队列中取出任务并调用任务 run() 方法。
因此,在本质上,executor.submit 帮你完成了 “创建 FutureTask + 启动线程执行” 这两步。
3. 获取结果(阻塞等待)
System.out.println(future.get());
此时 future 其实就是那个提交的 FutureTask 对象(只是用 Future 引用接口)。
FutureTask.get() 逻辑和你以前用的一样:
若任务尚未完成(run() 结果还没有写进去 outcome 当前线程(这里是当前线程) main 线程)会被堵塞。
阻塞通常通过 LockSupport.park() 实现并将等待一个 signal 唤醒。
执行工作线程时 FutureTask.run() 后:
调用 callable.call() 获得返回值(或捕获异常)。
保存结果(或异常) outcome 字段。
调用 finishCompletion() 方法,唤醒一切 get() 等待的线程。
被唤醒的 main 线程从 get() 返回,得到结果并打印。
public class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"...执行了");
}
}
public class Test01 {
public static void main(String[] args) {
///创建线程池对象
ExecutorService es = Executors.newFixedThreadPool(2);
es.submit(new MyRunnable());
es.submit(new MyRunnable());
es.submit(new MyRunnable());
//es.shutdown();///关闭线程池对象
}
}
public class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
return 1;
}
}
public class Test02 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService es = Executors.newFixedThreadPool(3);
Future<Integer> f1 = es.submit(new MyCallable());
Future<Integer> f2 = es.submit(new MyCallable());
Future<Integer> f3 = es.submit(new MyCallable());
Future<Integer> f4 = es.submit(new MyCallable());
Future<Integer> f5 = es.submit(new MyCallable());
System.out.println(f1.get());
System.out.println(f2.get());
System.out.println(f3.get());
System.out.println(f4.get());
System.out.println(f5.get());
}
}
具体流程图如下:
sequenceDiagram participant Main as 主线程 participant Pool as 线程池<br/>(3个工作线程) participant Queue as 阻塞队列<br/>(无界) Main->>Pool: submit(任务1) → f1 Main->>Pool: submit(任务2) → f2 Main->>Pool: submit(任务3) → f3 Note over Pool: 三个空闲线程立即分别执行任务1,2,3 Main->>Queue: submit(任务4) → f4 Main->>Queue: submit(任务5) → f5 Note over Queue: 任务4,5进入队列等待 Main->>Main: f1.get() 阻塞,等待任务1完成 par 任务1执行中 Pool->>Pool: 线程A 执行任务1 (耗时) and 任务2执行中 Pool->>Pool: 线程B 执行任务2 (耗时) and 任务3执行中 Pool->>Pool: 线程C 执行任务3 (耗时) end Note over Pool: 假设任务1首先完成 Pool-->>Main: 任务1完成,唤醒主线程 Main->>Main: f1.get() 返回,打印结果1 Main->>Main: f2.get() 堵塞,等待任务2完成 Note over Pool: 线程A是免费的,立即从队列任务4执行 Pool->>Pool: 线程A 执行任务4 Note over Pool: 完成任务2(可能已经同时完成) Pool-->>Main: 任务2完成,唤醒主线程 Main->>Main: f2.get() 返回,打印结果2 Main->>Main: f3.get() 堵塞,等待任务3完成 Note over Pool: 线程B是免费的,执行队列任务5 Pool->>Pool: 线程B 执行任务5 Note over Pool: 任务3完成 Pool-->>Main: 任务3完成,唤醒主线程 Main->>Main: f3.get() 返回,打印结果3 Note over Pool: 任务4、5还在执行中... Main->>Main: f4.get() 阻塞,等待任务4完成 Pool-->>Main: 任务4完成 Main->>Main: 打印结果4 Main->>Main: f5.get() 堵塞,等待任务5完成 Pool-->>Main: 任务5完成 Main->>Main: 打印结果5
练习需求:创建两个线程任务,一个线程任务完成1-100和,一个线程任务返回一个字符串
public class MyString implements Callable<String> {
@Override
public String call() throws Exception {
return “那天晚上,你没有拒绝我,那天晚上,你伤害了我。”;
}
}
public class MySum implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum+=i;
}
return sum;
}
}
public class Test01 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
///创建线程池对象
ExecutorService es = Executors.newFixedThreadPool(2);
Future<String> f1 = es.submit(new MyString());
Future<Integer> f2 = es.submit(new MySum());
System.out.println(f1.get());
System.out.println(f2.get());
}
}
第六章定时器_Timer
1.概述:定时器
2.构造:
Timer()
3.方法:
void schedule(TimerTask task, Date firstTime, long period)
task:抽象类是Runnable的实现类
firstTime:什么时候开始执行?
period: 每隔多长时间执行一次,设置毫秒值
public class demo01timer {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println(“金莲对陶哥说:陶哥,快起床~~~”);
}
},new Date(),2000L);
}
}