public class ThreadDemo12 {
public static void main(String[] args) {
goods g=new goods();
Product pro=new Product(g);
Thread th1=new Thread(pro);
th1.start();
Customer cus=new Customer(g);
Thread th2=new Thread(cus);
th2.start();
}
}
/**
* 商品类
* @author Al菜菜
*
*/
class goods {
private String name;
private int num;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setNum(int num) {
this.num = num;
}
public int getNum() {
return num;
}
/**
* 消费后将商品设为空值
*/
public void setEmpty(){
this.name=null;
this.num=0;
}
/**
* 判断是否有商品可以消费
* @return
*/
public boolean isEmpty(){
return this.name==null&&this.num==0;
}
}
class Product implements Runnable {
private boolean flag = false;//用于循环生产商品
private goods g;
public Product(goods g) {
this.g = g;
}
@Override
public void run() {
for (int i = 0; i < 30; i++) {
synchronized (Object.class) { //线程锁
if(!g.isEmpty()){
try {
Object.class.wait(); //当有商品没有被消费是,进入等待状态
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (flag) {
System.out.print("生产了商品一");
g.setName("商品一");
try {
Thread.sleep(100); //用于在不使用锁的情况下,触发现象
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("生产了20个");
g.setNum(20);
flag=false;
} else {
System.out.print("生产了商品二");
g.setName("商品二");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("生产了40个");
g.setNum(40);
flag=true;
}
Object.class.notify();
}
}
}
}
class Customer implements Runnable {
private goods g;
public Customer(goods g) {
this.g = g;
}
@Override
public void run() {
for(int i=0;i<30;i++){
synchronized (Object.class) {
if(g.isEmpty()){
try {
Object.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("消费商品:"+g.getName()+"数量:"+g.getNum());
g.setEmpty();
Object.class.notify();
}
}
}
}
生产了商品一生产了20个
消费商品:商品一数量:20
生产了商品二生产了40个
消费商品:商品二数量:40
生产了商品一生产了20个
消费商品:商品一数量:20
生产了商品二生产了40个
消费商品:商品二数量:40
生产了商品一生产了20个
消费商品:商品一数量:20
生产了商品二生产了40个
消费商品:商品二数量:40
生产了商品一生产了20个
消费商品:商品一数量:20
生产了商品二生产了40个
消费商品:商品二数量:40
生产了商品一生产了20个
消费商品:商品一数量:20
生产了商品二生产了40个
消费商品:商品二数量:40
生产了商品一生产了20个
消费商品:商品一数量:20
......