多线程 重点: 1.可以使用wait和notify两种方法 2.使用Lock锁对象 3.Callable接口将用于实现多线程 4.将使用线程池完成多线程 第一章等待唤醒机制 1.等待唤醒案例分析(线程之间的通信) 要求:线程生产,线程消费,不能连续生产,不能连续消费 -> 等待唤醒机制(生产者、消费者)(线程之间的通信) 方法 说明 void wait() 线程等待,线程在等待过程中释放锁,需要被其他线程叫醒,重新执行,但不会重新执行所有代码 void notify() 线程唤醒,一次唤醒等待线程;如果有多个线程等待,随机唤醒等待线程 void notifyAll() 唤醒所有等待线程
wait和notify方法需要对锁对象进行调用,因此需要在同步代码块中使用,必须是同一锁对象 2.等待唤醒案例的实现 /* 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.改变flag状态,为true,证明生产已完成,有包子了 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(); } } synchronized:无论是同步代码块还是同步方法,都需要在一对{}结束后释放锁对象 Lock:需要同步的代码由两种方法控制,更加灵活 第四章.Calable接口_实现多线程模式三 1.概述:Callable
sequenceDiagram participant Main as 主线程 participant Pool as 线程池
(3个工作线程) participant Queue as 阻塞队列
(无界) 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