package com.instances;
class Resource{
private String name;
private int count=1;
private boolean flag=false;
public synchronized void set(String name){
while (flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.name=name+count;
count++;
System.out.println(Thread.currentThread().getName()+"--生产者--"+this.name);
flag=true;
notifyAll();
}
public synchronized void out(){
while (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"--消费者----"+this.name);
flag=false;
notifyAll();
}
}
class Producer implements Runnable{
private Resource r;
public Producer(Resource r) {
this.r=r;
}
@Override
public void run() {
while (true) {
r.set("全聚德烤鸭");
}
}
}
class Customer implements Runnable{
private Resource r;
public Customer(Resource r) {
this.r=r;
}
@Override
public void run() {
while (true) {
r.out();
}
}
}
public class ProducerCustomer {
public static void main(String[] args) {
Resource r=new Resource();
Producer p=new Producer(r);
Customer c=new Customer(r);
Thread t1=new Thread(p);
Thread t2=new Thread(p);
Thread t3=new Thread(c);
Thread t4=new Thread(c);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Resource{
private String name;
private int count=1;
private boolean flag=false;
public synchronized void set(String name){
while (flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.name=name+count;
count++;
System.out.println(Thread.currentThread().getName()+"--生产者--"+this.name);
flag=true;
notifyAll();
}
public synchronized void out(){
while (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"--消费者----"+this.name);
flag=false;
notifyAll();
}
}
class Producer implements Runnable{
private Resource r;
public Producer(Resource r) {
this.r=r;
}
@Override
public void run() {
while (true) {
r.set("全聚德烤鸭");
}
}
}
class Customer implements Runnable{
private Resource r;
public Customer(Resource r) {
this.r=r;
}
@Override
public void run() {
while (true) {
r.out();
}
}
}
public class ProducerCustomer {
public static void main(String[] args) {
Resource r=new Resource();
Producer p=new Producer(r);
Customer c=new Customer(r);
Thread t1=new Thread(p);
Thread t2=new Thread(p);
Thread t3=new Thread(c);
Thread t4=new Thread(c);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
本文介绍了一个使用Java实现的生产者消费者模式案例。通过一个资源类Resource协调多个生产者与消费者的同步问题,确保在多线程环境下正确处理资源的生产和消费过程。
1216

被折叠的 条评论
为什么被折叠?



