Javaマルチスレッドアプリケーションプロデューサーコンシューマー問題コード

問題の概要:1つを生成し、1つを消費し、スレッドを同期させます

class Message {
    private String title;
    private String content;
    private boolean flag = true; //生産または消費を示します
    // flag = trueは生産を許可し
    ますが、消費は許可しません// flag = false消費は生産を許可しません
 public synchronized void set(文字列のタイトル、文字列の内容){
     if(this.flag == false){
         try {
            super.wait();
        } catch(InterruptedException e){
            // TODO自動生成されたcatchブロック
            e.printStackTrace();
        }
     }
     this。 title = title;
     try {
        Thread.sleep(100);
    } catch(InterruptedException e){
        // TODO自動生成されたcatchブロック
        e.printStackTrace();
    }
     this.content =コンテンツ;
     this.flag = false; //すでに発生した产完毕了
     super.notify(); //唤醒等待られた线程
 }
 public synchronized String get(){
     if(flag == true){
         try {
            super.wait();
        } catch(InterruptedException e){
            // TODO自動生成されたcatchブロック
            e.printStackTrace();
        }
     }
     {
        Thread.sleep(100);を試してください
    } catch(InterruptedException e){
        // TODO自動生成されたcatchブロック
        e.printStackTrace();
    }お試しください{
     return this.title + "-" + this.content;
    }最後に {
        this.flag = true;
        super.notify();
    }
 }
}

クラスProducerはRunnable {
private Message msg;を実装します。
public Producer(Message msg){
    this.msg = msg;
    
} @Override
    public void run(){
        // TODO自動生成されたメソッドスタブ
        for(int x = 0; x <100; x ++){
            if(x%2 == 0){
                this.msg.set( "王健"、"宇宙大帅哥 ");
                
                
            } else {
                this.msg.set( "赵高"、 "第一人");
            }
        }
    }
    
}

クラスConsumerはRunnable {
    private Message msg;を実装します。
    public Consumer(Message msg){
        this。
    }
    @Override
    public void run(){
     for(int x = 0; x <100; x ++){
         try {
            Thread.sleep(10);
        } catch(InterruptedException e){
            // TODO自動生成されたcatchブロック
            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(); //启动消费者线程
        
    }
 
}

おすすめ

転載: www.cnblogs.com/yxj808/p/12674954.html