一 概述:

多个线程执行不同任务获取同一个资源,此时需要线程通信来帮助解决线程之间对同一个变量的使用或操作。(避免对同一共享变量的争夺,导致死锁)

于是我们引出了等待唤醒机制:(wait()、notify())
就是在一个线程进行了规定操作后,就进入等待状态(wait),等待其他线程执行完他们的指定代码过后,再将其唤醒(notify);

二 案例:(生产者和消费者模式)

多个线程直接能够更好的沟通,协调配合工作
操作步骤:
1.生产者和消费者都去操作共享的资源
2.定义共享的资源
3.生产者和消费者进行加锁和解锁操作
wait() 和 notify()方法

共享资源

public class ShareResource {
private String name;
private int age;

//表示共享资源的状态(初始是空的)
boolean flag = true;

//生产者向共享资源中存储数据
public synchronized void push(String name, int age) {

    while (!flag) {
        try {
            this.wait();        //如果资源不为空,则生产者等待
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //生产开始
    this.name = name;
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    this.age = age;
    System.out.println("生产者是:" + this.name + ":" + this.age);

    //生产结束
    this.flag = false;      //将共享资源设置为不空
    this.notify();          //生产者唤醒消费者
}

//消费者向共享资源中取出数据
public synchronized void pull() {

    while (flag) {
        try {
            this.wait();        //如果资源为空,则消费者等待
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("消费者是:" + this.name + ":" + this.age);

    this.flag = true;   //将共享资源状态设置为空
    this.notify();      //消费者唤醒生产者
}

}

生产者

public class Product implements Runnable {

ShareResource resource = null;

public Product(ShareResource resource) {
    this.resource = resource;
}

@Override
public void run() {
    for (int i = 0; i < 20; i++) {
        if (i % 2 == 0) {
            resource.push("张三", 23);
        } else {
            resource.push("李四", 24);
        }
    }
}

}

消费者

public class Consumer implements Runnable {

ShareResource resource = null;

public Consumer(ShareResource resource) {
    this.resource = resource;
}

@Override
public void run() {
    for (int i = 0; i < 20; i++) {
        resource.pull();
    }
}

}

测试类

public class Test6 {
public static void main(String[] args) {
    //创建共享资源对象
    ShareResource resource=new ShareResource();

    //创建自定义线程对象
    Product product=new Product(resource);
    Consumer consumer=new Consumer(resource);

    //创建线程对象
    Thread t1=new Thread(product);
    Thread t2=new Thread(consumer);

    //启动线程
    t1.start();
    t2.start();
}

}