关于消费者-生产者问题的服务器和客户端的RMI实现正确吗?

时间:2019-07-09 15:23:28

标签: java multithreading rmi producer-consumer

由于我刚开始学习RMI概念,所以我想知道我的实现是否正确。 因此,有N个使用相同代码的客户端(请参阅实现)和一台服务器。客户端的工作方式类似于使用RMI概念访问相同缓冲区的使用者。 服务器本身有一个生产者,可以将项目放入缓冲区。缓冲区的最大大小为20。可以访问缓冲区。

问题是:我的实施能否正常工作? 不要介意例外。

提前谢谢!

public class Buffer
{
   private Vector<Integer> buffer;
   private Semaphor mutex;
   private boolean flag1;
   private boolean flag2;   

   public Buffer()
   {
      buffer = new Vector<Integer> buffer;
      mutex = new Semaphor(1);
      flag1 = false;
      flag2 = false;
   }

   public synchronized Integer get()
   {
      if (buffer.size() == 0)
      {
         flag1 = true;

         if(flag2)
         {
            notify();
         }

         try
         {
            wait();
         } catch(Exception e)
         {}
       }

       mutex.p();
       Integer temp = buffer.lastElement();
       buffer.remove(temp);
       mutex.v();

       return temp;
    }

    public synchronized void put(Integer a)
   {
      if (buffer.size() == 20)
      {
         flag2 = true;

         if(flag1)
         {
            notify();
         }

         try
         {
            wait();
         } catch(Exception e)
         {}
       }

       mutex.p();
       buffer.add(a);
       mutex.v();
    }
}



public interface Consumer extends Remote
{
   public Integer get() throws RemoteException;
}



public class ConsumerImpl extends UnicastRemoteObject implements Consumer
{
   private Buffer buffer;

   public ConsumerImpl(Buffer buff) throws RemoteException
   {
      buffer = buff;
   }

   public Integer get() throws RemoteException
   {
      return buffer.get();
   }
}



public class Producer extends Thread
{
   private Buffer buffer;

   public Producer(Buffer buff)
   {
      buffer = buff;
      this.start();
   }

   public void run()
   {
      Integer a = 0;

      while (true)
      {
         buffer.put(a);

         try
         {
            sleep(1000);
         }
         catch (Exception e) {}
      }
   }
}



public class Server
{
   public static void main(String[] args)
   {
      try
      {
         Buffer buffer = new Buffer();
         ConsumerImpl c1 = new ConsumerImpl(buffer);
         Producer prod = new Producer(buffer);
         Naming.rebind("Server1", c1);
       }
       catch(Exception e)
       {
          return;
       }
   }
}



public class Client_J
{
   public static void main(String[] args)
   {
      try
      {
         Consumer c1 = (Consumer) Naming.lookup("rmi://" + args[0] +   "/Server1");

         while(true)
         {
            System.out.println(c1.get());
         }
       }
       catch(Exception e)
       {
           return;
       }
   }
}

0 个答案:

没有答案