1.代码
package com.example.test.demo.thread;
import java.util.Date;
/**
* @author 王健宇
* @title: WaitNotifyDemo
* @description
* @date 2021/6/26 10:41
*/
public class WaitNotifyDemo {
// 消费产品
class User {
String name; //姓名
String sex; //性别
/**
* 控制消费生产,true 表示可以生成 false 表示可以输出,最终达成生产一个输出一个 交替执行
*/
boolean flag = false;
}
/**
* 生产者
*/
class Product extends Thread {
User User;
public Product(User User) {
this.User = User;
}
@Override
public void run() {
int count = 0;
while (true) {
synchronized (User) {
if (!User.flag) {
try {
User.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (count == 0) {
User.name = "张三";
User.sex = "男";
} else {
User.name = "李四";
User.sex = "女";
}
if (User.flag) {
User.notify();
User.flag = false;
}
count = (count + 1) % 2;
}
}
}
}
/**
* 消费者
*/
class Customer extends Thread {
User User;
public Customer(User User) {
this.User = User;
}
@Override
public void run() {
while (true) {
synchronized (User) {
if (User.flag) {
try {
User.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("姓名:"+ User.name +"性别:" + User.sex);
if (!User.flag) {
User.notify();
User.flag = true;
}
}
}
}
}
public static void main(String[] args) {
// 创建公共资源对象
WaitNotifyDemo demo = new WaitNotifyDemo();
User User = demo.new User();
demo.new Product(User).start();
demo.new Customer(User).start();
}
}
2.输出
姓名:张三性别:男
姓名:李四性别:女
姓名:张三性别:男
姓名:李四性别:女
姓名:张三性别:男
姓名:李四性别:女
姓名:张三性别:男
姓名:李四性别:女
姓名:张三性别:男
姓名:李四性别:女
姓名:张三性别:男
姓名:李四性别:女
..............