java多线程的应用 生产者消费者问题代码

问题概述:生产一个消费一个,保持线程同步

class Message{
    private String title;
    private String content;
    private boolean flag=true;//表示生产或者消费
    //flag =true 允许生产,但是不允许消费
    //flag =false 允许消费 不允许生产
 public synchronized void set(String title,String content) {
     if(this.flag==false) {
         try {
            super.wait();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
     }
     this.title=title;
     try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
     this.content=content;
     this.flag=false;//已经生产完毕了
     super.notify();//唤醒等待的线程
 }
 public synchronized String get() {
     if(flag==true) {
         try {
            super.wait();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
     }
     try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }try {
     return this.title+"-"+this.content;
    }finally {
        this.flag=true;
        super.notify();
    }
 }
}

class Producer implements Runnable{
private Message msg;
public Producer(Message msg) {
    this.msg=msg;
    
}@Override
    public void run() {
        // TODO Auto-generated method stub
        for(int x=0;x<100;x++) {
            if(x%2==0) {
                this.msg.set("王健","宇宙大帅哥");
                
                
            }else {
                this.msg.set("赵高","第一人");
            }
        }
    }
    
}

class Consumer implements Runnable{
    private Message msg;
    public Consumer(Message msg) {
        this.msg=msg;
    }
    @Override
    public void run() {
     for(int x=0;x<100;x++) {
         try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         System.out.println(this.msg.get());
     }
        
    }
    
}

 
 
public class Test1 {
     public static void main(String[] args) throws Exception {
  Message msg=new Message();
  new Thread(new Producer(msg)).start();//启动生产者线程
  new Thread(new Consumer(msg)).start();//启动消费者线程
        
    }
 
}

原文地址:https://www.cnblogs.com/yxj808/p/12674954.html