java同步问题

野树林 野树林 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区


Bread.java

public class Bread {
private int counts;
private static int flag;

public Bread(int counts) {
this.counts = counts;
Bread.flag = 0;// 没有面包
}

public synchronized void set() {
if (flag != 0) {
try {
wait();
} catch (InterruptedException e) {
}
}
System.out.println("开始生产");
for (int i = 1; i <= counts; ++i) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println(i + "个");
flag++;
}
System.out.println("生产完毕");
notifyAll();
}

public synchronized void get() {
if (flag == 0) {
System.out.println("启动消费");
System.out.println("还没有生产出面包,等待中...");
try {
wait();
} catch (InterruptedException e) {
}
}
System.out.println("开始消费");
for (int i = counts; i >= 1; --i) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println(i + "个");
flag--;
}
System.out.println("消费完毕。");
notify();
}
}

Customor.java

public class Customor implements Runnable{
Bread bre = new Bread(5);
public void run() {
bre.get();
}
}

Productor.java

public class Prodctor implements Runnable {
Bread bre = new Bread(5);
public void run() {
bre.set();
}

}

BreadMain.java

public class BreadMain {
public static void main(String[] args){
Prodctor pro = new Prodctor();
Customor cut = new Customor();
Thread proct = new Thread(pro);
Thread custom = new Thread(cut);
custom.start();
proct.start();
}
}


程序 要求:
(1) 一次 生产 5个面包,一次 消费 5个面包。
(2) 注意 同步 机制 , wait()方法 ,no tify() 方法 的使用。

各位看看有啥问题???谢谢!!!
...全文

相关推荐

评论 6
收藏 已收藏
分享
返回顶部
野树林
Java SE 62,620 成员 307,251 内容