⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 complete11_4.java

📁 北京大学出版社的
💻 JAVA
字号:
package questions.c11;
import java.util.Random;
/** Class representing a message queue with one slot
  * The add and get methods are synchronized
  */
public class Complete11_4 {
   private String message;
   private boolean keepGoing = true;
   /** Worker class that continuously writes to the
     * message queue and sleeps for a random period
     * of time.
     */
   class MessageWriter extends Thread {
      /** Continuously write, then sleep */
      public void run() {
         int ms;
         Random r = new Random();
         while( keepGoing ) {
            Complete11_4.this.addMessage( "test message" );
            try {
               ms = (int)(100 * r.nextDouble());
               Thread.currentThread().sleep( ms );
            } catch ( InterruptedException ix ) {
               // ignore it
            }
         }
      }
   }
   // Add your MessageReader inner class here
   /** Add a message to the queue, but wait until it
     * is empty
     * @param m the message being added
     */
   public synchronized void addMessage( String m ) {
      // Your code here
   }
   /** Take a message from the queue, but wait until
     * there is something to take
     * @return the message
     */
   public synchronized String getMessage() {
      while ( message == null && keepGoing ) {
         // wait for a message to be placed
         try {
            System.out.println(
                              "Waiting to get..." );
            wait();
         } catch( InterruptedException ix ) {
            // ignore it
         }
      }
      String temp = null;
      if ( keepGoing ) {
         temp = message;
         message = null;
      }
      notifyAll();
      return temp;
   }
   public void requestStop() {
      keepGoing = false;
   }
   /** Test method
     * @param args not used
     */
   public static void main( String[] args )
                        throws InterruptedException {
      Complete11_4 mq = new Complete11_4();
      MessageReader reader = mq.new MessageReader();
      MessageWriter writer = mq.new MessageWriter();
      reader.start();
      writer.start();
      try {
         Thread.currentThread().sleep( 20000 );
      } finally {
         mq.requestStop();
      }
   }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -