1、应用场景:生产者和消费者问题
- 假设仓库中只能存放一件产品,生产者将生产出来的产品放入仓库,消费者将仓库中产品取走消费
- 如果仓库中没有产品,则生产者将产品放入仓库,否则停止生产并等待,直到仓库中的产品被消费者取走为止
- 如果仓库中放有产品,则消费者可以将产品取走消费,否则停止消费并等待,直到仓库中再次放入产品为止
- 分析
- 这是一个线程同步问题,生产者和消费者共享同一个资源,并且生产者和消费者之间相互依赖,互为条件
- 对于生产者,没有生产产品之前,要通知消费者等待。而生产了产品之后,又需要马上通知消费者消费
- 对于消费者,在消费之后,要通知生产者已经消费结束,需要继续生产新产品以供消费
- 在生产者消费者问题中,仅有synchronized是不够的
- synchronized可阻止并发更新同一个共享资源,实现了同步
- synchronized不能用来实现不同线程之间的消息传递(通信)
1.1 Java提供了3个方法解决线程之间的通信问题
注意事项
- 均是lang.Object类的方法
- 都只能在同步方法或者同步代码块中使用,否则会抛出异常
- 必须调用同步监视器的wait() notify() notifyAll()方法
2、实战消费者与生产者
2.1 准备阶段
2.1.1 Product类
- 属性
- name 商品名称
- color 商品颜色
- flag 商品是否生产
public class Product {
private String name;
private String color;
private boolean flag=false;
public Product(String name, String color) {
this.name = name;
this.color = color;
}
public Product() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public String toString() {
return "Product{" +
"name='" + name + '\'' +
", color='" + color + '\'' +
'}';
}
}
2.1.2 Test类
- 创建一个公共的产品库(在此用一个商品表示)
- 创建两个线程,消费者线程和生产者线程
- 创建的商品需传入给两个线程,保证两个线程访问的是同一个商品
public class Test {
public static void main(String[] args) {
Product product=new Product();
//创建线程
Runnable runnable1=new ProduceRunnable(product);
Thread thread1=new Thread(runnable1);
Runnable runnable2=new ConsumerRunnable(product);
Thread thread2=new Thread(runnable2);
//执行线程
thread1.start();
thread2.start();
}
}
2.2 使用同步代码块来实现线程通信
2.2.1 ProduceRunnable类
- 属性:product。注意不要对其进行初始化,需要保证其是外部传入的,否则无法实现。
- 线程通信逻辑步骤
- 如果有商品则等待。
- 如果没有商品则生成商品
- 生产完之后改变商品的flag属性,表示其已经生产
- 调用product.notify()方法,随机唤醒一个等待队列中的线程
public class ProduceRunnable implements Runnable{
private Product product;
public void setProduct(Product product) {
this.product = product;
}
public ProduceRunnable(Product product) {
this.product = product;
}
public ProduceRunnable() {
}
@Override
public void run() {
int i=500;
while (true){
synchronized (product){
if(i<=0){
break;
}
//如果有商品,则等待
if (product.isFlag()){
try {
product.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(i%2==0){
product.setName("米饭");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
product.setColor("白色");
}else {
product.setName("玉米");
product.setColor("黄色");
}
i--;
//改变商品状态
product.setFlag(true);
System.out.println("生产者生产了商品"+product.getName()+product.getColor());
product.notify();
}
}
}
}
2.2.2 ConsumerRunnable类
- 属性:product同上
public class ConsumerRunnable implements Runnable{
private Product product;
public void setProduct(Product product) {
this.product = product;
}
public ConsumerRunnable(Product product) {
this.product = product;
}
public ConsumerRunnable() {
}
@Override
public void run() {
int i=500;
while (true){
synchronized (product){
if (i<=0){
break;
}
if(!product.isFlag()){
try {
product.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("消费者消费了商品"+product.getName()+product.getColor());
product.setFlag(false);
i--;
product.notify();
}
}
}
}
2.3 运行结果
2.4 使用同步方法来实现线程通信
2.4.1 Product类
- 将生产和消费的同步方法封装到该类中。
public class Product {
private String name;
private String color;
private boolean flag=false;
public Product(String name, String color) {
this.name = name;
this.color = color;
}
public Product() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public String toString() {
return "Product{" +
"name='" + name + '\'' +
", color='" + color + '\'' +
'}';
}
public synchronized void produce(int i){
//如果有商品,则等待
if (this.isFlag()){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(i%2==0){
this.setName("米饭");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.setColor("白色");
}else {
this.setName("玉米");
this.setColor("黄色");
}
//改变商品状态
this.setFlag(true);
System.out.println("生产者生产了商品"+this.getName()+this.getColor());
this.notify();
}
public synchronized void consume(){
if(!this.isFlag()){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("消费者消费了商品"+this.getName()+this.getColor());
this.setFlag(false);
this.notify();
}
}
2.4.2 ProduceRunnable类
public class ProduceRunnable implements Runnable{
private Product product;
public void setProduct(Product product) {
this.product = product;
}
public ProduceRunnable(Product product) {
this.product = product;
}
public ProduceRunnable() {
}
@Override
public void run() {
int i=500;
while (true){
if(i<=0){
break;
}
product.produce(i);
i--;
}
}
}
2.4.3 ConsumerRunnable类
public class ConsumerRunnable implements Runnable{
private Product product;
public void setProduct(Product product) {
this.product = product;
}
public ConsumerRunnable(Product product) {
this.product = product;
}
public ConsumerRunnable() {
}
@Override
public void run() {
int i=500;
while (true){
if (i<=0){
break;
}
product.consume();
i--;
}
}
}
2.4.4 Test类
同上
2.5 使用Lock锁实现
2.5.1 修改product类即可,其余的同2.4
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Product {
private String name;
private String color;
private boolean flag=false;
private Lock lock=new ReentrantLock();
private Condition produceCondition= lock.newCondition();
private Condition consumeCondition= lock.newCondition();
public Product(String name, String color) {
this.name = name;
this.color = color;
}
public Product() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public String toString() {
return "Product{" +
"name='" + name + '\'' +
", color='" + color + '\'' +
'}';
}
public synchronized void produce(int i){
//如果有商品,则等待
lock.lock();
try {
if (this.isFlag()){
try {
//this.wait();
produceCondition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(i%2==0){
this.setName("米饭");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.setColor("白色");
}else {
this.setName("玉米");
this.setColor("黄色");
}
//改变商品状态
this.setFlag(true);
System.out.println("生产者生产了商品"+this.getName()+this.getColor());
consumeCondition.signal();
}finally {
lock.unlock();
}
}
public synchronized void consume(){
lock.lock();
try {
if(!this.isFlag()){
try {
consumeCondition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("消费者消费了商品"+this.getName()+this.getColor());
this.setFlag(false);
produceCondition.signal();
}finally {
lock.unlock();
}
}
}
2.5.2 Condition
Condition是在Java 1.5中才出现的,它用来替代传统的Object的wait()、notify()实现线程间的协作,相比使用Object的wait()、notify(),使用Condition1的await()、signal()这种方式实现线程间协作更加安全和高效。
它的更强大的地方在于:能够更加精细的控制多线程的休眠与唤醒。对于同一个锁,我们可以创建多个Condition,在不同的情况下使用不同的Condition
一个Condition包含一个等待队列。一个Lock可以产生多个Condition,所以可以有多个等待队列。
在Object的监视器模型上,一个对象拥有一个同步队列和等待队列,而Lock(同步器)拥有一个同步队列和多个等待队列。
Object中的wait(),notify(),notifyAll()方法是和"同步锁"(synchronized关键字)捆绑使用的;而Condition是需要与"互斥锁"/"共享锁"捆绑使用的。
调用Condition的await()、signal()、signalAll()方法,都必须在lock保护之内,就是说必须在lock.lock()和lock.unlock之间才可以使用
- Conditon中的await()对应Object的wait();
- Condition中的signal()对应Object的notify();
- Condition中的signalAll()对应Object的notifyAll()。
void await() throws InterruptedException
造成当前线程在接到信号或被中断之前一直处于等待状态。
与此 Condition 相关的锁以原子方式释放,并且出于线程调度的目的,将禁用当前线程,且在发生以下四种情况之一 以前,当前线程将一直处于休眠状态:
- 其他某个线程调用此 Condition 的 signal() 方法,并且碰巧将当前线程选为被唤醒的线程;或者
- 其他某个线程调用此 Condition 的 signalAll() 方法;或者
- 其他某个线程中断当前线程,且支持中断线程的挂起;或者
- 发生“虚假唤醒”
在所有情况下,在此方法可以返回当前线程之前,都必须重新获取与此条件有关的锁。在线程返回时,可以保证它保持此锁。
void signal()
唤醒一个等待线程。
如果所有的线程都在等待此条件,则选择其中的一个唤醒。在从 await 返回之前,该线程必须重新获取锁。
void signalAll()
唤醒所有等待线程。
如果所有的线程都在等待此条件,则唤醒所有线程。再从 await 返回之前,每个线程都必须重新获取锁。
3、线程同步的细节
- 进行线程通信的多个线程,要使用同一个同步监视器(product),还必须要调用该同步监视器的wait()、notify()、notifyAll();
- 线程通信的三个方法
-
wait()等待
在其他线程调用此对象的notify()或notifyAll()方法前,导致当前线程等待。换句话说,此方法的行为就好像它仅执行 wait(0) 调用一样。当前线程必须拥有此对象监视器。
-
wait(time) 等待
在其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者超过指定的时间量前,导致当前线程等待。 当前线程必须拥有此对象监视器
-
notify() 通知 唤醒
唤醒在【此对象监视器】上等待的【单个】线程。如果所有线程都在此对象上等待,则会选择唤醒其中一个线程。【选择是任意性的】,并在对实现做出决定时发生
-
notifyAll() 通知所有 唤醒所有
唤醒在【此对象监视器】上等待的【所有】线程。被唤醒的线程将以常规方式与在该对象上主动同步的其他所有线程【进行竞争】
-
3.1 完整的线程生命周期
三种阻塞状态
- 普通的阻塞:经sleep、join、Scanner等导致的阻塞
- 同步阻塞(锁池状态) 没有获取同步监视器的线程的队列(比如两个线程竞争同一个资源,一个线程率先获得并上锁,则另一个线程则为同步阻塞状态)
- 等待阻塞(阻塞队列) 被调用了wait()后释放锁,然后进入该队列
3.2 sleep()和wait()的区别
- sleep()会让该线程让出CPU进入普通阻塞状态,但不会释放锁。wait()会让线程让出CPU进入等待阻塞状态,并且会释放锁,进入等待此对象的等待锁定池
- 进入的阻塞状态也是不同的队列
- wait只能在同步控制方法或者同步控制块里面使用,而sleep可以在任何地方使用。