如何在java中启动远程线程?

时间:2014-02-23 07:09:57

标签: java multithreading producer-consumer

我有一个应用程序,其中有三个文件夹。我正在尝试使用LinkedBlockingQueue实现生产者消费者概念。

文件夹1: 包含具有共享队列的类

public static BlockingQueue sharedQueue = new LinkedBlockingQueue();

从这个类的方法中,我尝试调用Producer线程和Consumer线程,这两个线程都驻留在不同的文件中。

  Thread updateThread = new Thread(new Producer(sharedQueue));
  Thread takeThread = new Thread(new Consumer(sharedQueue));
  updateThread.start();
  takeThread.start();

文件夹2:包含生产者线程类,如下所示:

public class Producer implements Runnable {        
    private final BlockingQueue Queue;

    public Producer(BlockingQueue sharedQueue){    
        Queue = sharedQueue;
    }

    public void run()
    {
         while (Thread.currentThread() != null) {
         Random random = new Random();
         int pos = random.nextInt(productList.size());              
         String query = "insert into tab1 values("+pos+")";
         Queue.put(query);  
    }
}

文件夹3:包含消费者类,如下所示:

public class Consumer implements Runnable{

    private final BlockingQueue queue;
    Collection<String> joblist;   
    public Consumer (BlockingQueue sharedQueue) {
    queue = sharedQueue;
    MonitoringForm.txtInforamtion.append("hi"+sharedQueue.size());
    joblist = new ArrayList<String>();
}

@Override
public void run() {

    while(true){
        try {             
            for(int i = 0; i < queue.size(); i++)
            {
                joblist.add(queue.take().toString());
                MonitoringForm.txtInforamtion.append("What we got "+queue.take().toString());
            }
        } catch (InterruptedException ex) {
            Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            Thread.sleep(60*1000); 
        } catch (Exception e) {
     }

    }
}
}

有人可以告诉我如何确保Producer类添加到共享队列的数据可以由Consumer类获取。消费者每分钟都会消耗数据。数据生成后不必立即使用。调用Consumer和Producer线程不起作用,因为我将它们放在不同的目录中。我是否必须使用远程方法调用?线程有可能吗?

3 个答案:

答案 0 :(得分:1)

以下是我编写的示例代码,可以帮助您理解这个概念:

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * We want a Producer thread to create random values, and the Consumer thread to
 * consume it. One caveat is that if the Producer has already created a random
 * value, which the Consumer thread hasn't consumed yet, the Producer thread
 * blocks or waits. On the flip side, the Consumer thread waits for the Producer
 * thread to produce some value if the Producer thread hasn't already.
 * 
 * Write a program to simulate such a situation.
 */

public class ProducerConsumerCommunication
{

  private volatile boolean running = true;
  private ArrayBlockingQueue<Integer> buffer = new ArrayBlockingQueue<>(1);
  private Random random = new Random(System.currentTimeMillis());

  private class ProducerTask implements Runnable
  {
    public void run()
    {
      while (running)
      {
        try
        {
          Thread.sleep(random.nextInt(2000));
          Integer value = random.nextInt();
          buffer.put(value); // Blocks if buffer is full.
          System.out.println("Value Put: " + value);
        }
        catch (InterruptedException e)
        {
          e.printStackTrace();
        }
      }
    }
  }

  private class ConsumerTask implements Runnable
  {
    public void run()
    {
      while (running)
      {
        try
        {
          Thread.sleep(random.nextInt(2000));
          Integer value = buffer.take(); // Blocks if buffer is empty.
          System.out.println("Value Taken: " + value);
        }
        catch (InterruptedException e)
        {
          e.printStackTrace();
        }
      }
    }
  }

  public ProducerConsumerCommunication()
  {
    ExecutorService service = Executors.newCachedThreadPool();
    service.execute(new ProducerTask());
    service.execute(new ConsumerTask());
    service.shutdown();
  }

  public static void main(String[] args)
  {
    new ProducerConsumerCommunication();
  }
}

答案 1 :(得分:0)

在传统的消费者/生产者概念中,消费者等待资源。每当Producer在Queue上推送任何内容时,它都会通过notify()/ notifyAll()

通知Consumer。

制片人:

queue.put(query) ;
obj.notifyAll();

消费者:

while(true)
{
 try {
        obj.wait();
 }catch (InterruptedException e) { 
     } 
// get data from Queue
data = queue.take();

}

有关详细信息,请参阅以下链接:example

答案 2 :(得分:0)

以生产者和生产者的方式运行生产者和消费者,就像生产者在队列中生成某些东西一样,他应该通知消费者,当消费者从队列中消费时,他应该通知生产者在队列中生成某些东西,

要以这种方式实现您的问题,您必须使用

如果你有一个生产者和一个消费者,那么

等待和通知方法。 如果你有多个消费者,那么你必须使用NotifyAll方法以及Object Class,

在你的消费者中,如果你将这一行打印到你的控制台“我们得到了什么”,那么你确定消费者已经从队列中消耗了一些东西