如何用信号量代替synchronized、wait、notify?(生产者-消费者)

Dav*_*vid 5 java semaphore synchronized notify wait

晚上好,

我想知道如何用信号量替换下面代码中的同步、等待和通知?我必须在哪里创建信号量变量?

   import java.util.*;

   class Producer
   extends Thread
   {
     private Vector v;

     public Producer(Vector v)
     {
       this.v = v;
     }

     public void run()
     {
       String s;

       while (true) {
         synchronized (v) {
           s = "Value"+Math.random();
           v.addElement(s);
           System.out.println("Producer created "+s);
           v.notify();
         }
         try {
           Thread.sleep((int)(100*Math.random()));
         } catch (InterruptedException e) {
           //nothing
         }
       }
     }
   }

   class Consumer
   extends Thread
   {
      private Vector v;

      public Consumer(Vector v)
      {
         this.v = v;
      }

      public void run()
      {
         while (true) {
            synchronized (v) {
               if (v.size() < 1) {
                  try {
                     v.wait();
                  } catch (InterruptedException e) {
                     //nothing
                  }
               }
               System.out.print(
                 " Consumer found "+(String)v.elementAt(0)
               );
               v.removeElementAt(0);
               System.out.println(" (remaning: "+v.size()+")");
            }
            try {
               Thread.sleep((int)(100*Math.random()));
            } catch (InterruptedException e) {
               //nothing
            }
         }
      }
   }
Run Code Online (Sandbox Code Playgroud)

如果有人能帮助我,我会很高兴!

先感谢您..

nLe*_*Lee 4

将信号量视为可以允许多个线程访问共享资源的锁。无论您将信号量初始化为多少,都将允许许多线程同时访问资源。在生产者-消费者中,资源是两个线程之间的共享缓冲区。您需要确保消费者无法访问缓冲区(除非缓冲区已满),并且生产者无法访问缓冲区(除非缓冲区为空)。您应该从消费者信号量中的计数 0 和生产者信号量中的 1 开始。这样生产者就必须迈出第一步。当Producer开始写入缓冲区时,你要向downProducer发出信号量。当生产者完成后,您需要up消费者的信号量,这将允许消费者访问资源。当消费者访问资源时,它会up向生产者发送信号量,通知生产者缓冲区现在为空。

以此为起点:http://cs.gmu.edu/cne/modules/ipc/aqua/ Producer.html