美文网首页
多线程生产者和消费者模式

多线程生产者和消费者模式

作者: 皓皓amous | 来源:发表于2023-10-31 17:52 被阅读0次
public class TestBox {
   private String TAG = "TestBox";
   private int mile;
   private boolean status;

   public synchronized void getMile() {
       if (!status) {
           try {
               wait();
           } catch (InterruptedException e) {
               throw new RuntimeException(e);
           }
       }
       Log.d(TAG, "testSQ" + " 消费者取 " + this.mile + " " + "瓶奶");
       status = false;
       notifyAll();
   }

   public synchronized void putMile(int mile) {
       if (status) {
           try {
               wait();
           } catch (InterruptedException e) {
               throw new RuntimeException(e);
           }
       }

       this.mile = mile;
       status = true;
       Log.d(TAG, "testSQ" + " 送奶工 " + mile + " " + "瓶奶");
       notifyAll();

   }
}



public class TestCustomRunable implements Runnable {
   private TestBox testBox;

   public TestCustomRunable(TestBox testBox) {
       this.testBox = testBox;
   }

   @Override
   public void run() {
       while (true) {
           testBox.getMile();
       }
   }
}


public class TestProductRunable implements Runnable {
   private TestBox testBox;

   public TestProductRunable(TestBox testBox) {
       this.testBox = testBox;
   }

   @Override
   public void run() {
       for (int i = 0; i < 13; i++) {
           testBox.putMile(i);
       }
   }
}


相关文章

网友评论

      本文标题:多线程生产者和消费者模式

      本文链接:https://www.haomeiwen.com/subject/mmxwidtx.html