看完视频后总结,
第一种方法- package org.heima1;
- public class Test7 {
- /**
- * 生产者消费者问题
- */
- public static void main(String[] args) {
- Resource r=new Resource();
- productor p=new productor(r);
- consumer c=new consumer(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=0;
- private Boolean flag=false;
-
- public synchronized void set(String name){
- while(flag){ //必须用while循环判断,如果用if,就会出现极端情况
- try {
- wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- this.name=name+"----"+count++;
- System.out.println(Thread.currentThread().getName()+"。。。生产者。。。"+this.name);
- flag=true;
- notifyAll();//必须用notifyAll,防止只唤醒自己的线程
- }
- public synchronized void out(){
-
- while(!flag){ //必须用while循环判断,如果用if,就会出现极端情况
- try {
- wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- System.out.println(Thread.currentThread().getName()+"。消费者。。"+this.name);
- flag=false;
- notifyAll();//必须用notifyAll,防止只唤醒自己的线程
- }
- }
- class productor implements Runnable{
- private Resource r;
- productor(Resource r){
- this.r=r;
- }
- public void run(){
- while(true){
- r.set("商品");
- }
- }
- }
- class consumer implements Runnable{
- private Resource r;
- consumer(Resource r){
- this.r=r;
- }
- public void run(){
- while(true){
- r.out();
- }
- }
- }
复制代码 第二种方法解决
|
|