代码拉取完成,页面将自动刷新
当一个线程完成了一个任务的时候,要通知另外一个线程去处理其他 的事情。
问题1: 价格错乱.. (线程安全问题)
问题2:生产一个、消费一个。
/**
* 产品类
*/
class Product{
String name;
int price;
boolean flag ; //产品是否生成完毕的标识 false为还没有生成完毕, true 生成完毕了.
}
/**
* 生产者类
*/
class Producer extends Thread{
//维护一个产品
Product p;
public Producer(Product p){
this.p = p;
}
@Override
public void run() {
int i = 0;
while(true){
synchronized (p) {
if(p.flag==false){
if(i%2==0){
p.name = "摩托车";
p.price= 4000;
}else{
p.name = "自行车";
p.price = 300;
}
System.out.println("生产了"+ p.name+" 价格:"+ p.price);
i++;
//生成完毕 --- 改标识
p.flag = true;
//唤醒消费者去消费
p.notifyAll();
}else{
//如果产品已经生产完毕,应该等待消费者先消费
try {
p.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
//消费者
class Customer extends Thread{
//产品
Product p;
public Customer(Product p){
this.p = p;
}
@Override
public void run() {
while(true){
synchronized (p) {
if(p.flag==true){
System.out.println("消费者消费了:"+ p.name+" 价格:"+ p.price);
//改标识
p.flag = false;
p.notifyAll();
}else{
//如果产品已经被消费完毕,应该唤醒生产者去生成
try {
p.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public class Demo7 {
public static void main(String[] args) {
//创建一个产品对象
Product p = new Product();
//创建线程对象
Producer producer = new Producer(p);
Customer customer = new Customer(p);
//启动线程
producer.start();
customer.start();
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。