700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 用java编写生产者消费者问题_用java代码实现生产者和消费者的问题

用java编写生产者消费者问题_用java代码实现生产者和消费者的问题

时间:2023-07-07 08:18:13

相关推荐

用java编写生产者消费者问题_用java代码实现生产者和消费者的问题

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

......

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。