- package prouderComsumer;
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- //多线程间通信问题 <生产烤鸭问题>
- /*resoures producer consumer 和主函数创建线程4个类。resoures定义生产和消费的方法,producer和consumer定义接受resoures的构造函数
- * ,并实现多线程。*/
- public class ProuderComsumerDemo {
- public static void main(String[] args) {
- resoures r = new resoures();
- producer pro = new producer(r);
- consumer con =new consumer(r);
- Thread t1 = new Thread(pro);
- Thread t2 = new Thread(pro);
- Thread t3 = new Thread(con);
- Thread t4 = new Thread(con);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
- //资源
- class resoures {
- //定义变量:生产什么。生产多少了,生产与消费之间的切换变量
- private String name;
- private int count=0;
- private boolean falg =false;
- //生产方法
-
- public synchronized void set(String name){
- // 什么时候生产
-
- while(falg)
- try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}//睡觉
- //生产
- count++;
- if(count==1000){
-
- }
- this.name = name+count;
- System.out.println(Thread.currentThread().getName()+"生 产 了"+this.name);
- //生产完了要告诉消费者
- falg=true;
- notifyAll();
-
-
- }
- //消费方法
- public synchronized void out(){
- while(!falg)
- try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}
-
- System.out.println(Thread.currentThread().getName()+"消 费 了"+this.name);
- falg=false;
- notifyAll();
- }
- }
- //生产者
- class producer implements Runnable{
- private resoures r;
-
- public producer(resoures r) {
- super();
- this.r = r;
- }
- @Override
- public void run() {
- while(true){
- r.set("烤鸭");
-
- }
-
- }
-
- }
- //消费者
- class consumer implements Runnable{
- private resoures r;
-
- public consumer(resoures r) {
- super();
- this.r = r;
- }
- @Override
- public void run() {
- while(true){
- r.out();
-
-
-
- }
-
- }
- }
复制代码
上面的问题怎么没代码 ,郁闷。。。。。 |