-1

I am almost a newbie in java threading. I have a scenario whereby I am posting JSON messages in a rabbitmq queue and an external service is performing operation on the JSON received and then after the execution of the external service, it will return a value in integer indicating whether the execution went successful or not.

I want to call the external service and then want to wait for the return value i.e make the execution of the producer halt until consumer function returns me the value.

Your help is highly appreciable. Just give me the topic like whether to use synchronized methods, or Future and Callable interfaces etc.

Thanks. Please don't say that "show us what you have tried till now etc", I just need your suggestions about how to do it. :)

4

2 回答 2

1

看看我前段时间尝试的一个经典的生产者-消费者问题......没有原始博客/教程的链接,但这里是代码:

 public class ProducerConsumerTest {
  public static void main(String[] args) {
    CubbyHole c = new CubbyHole();
    Producer p1 = new Producer(c, 1);
    Consumer c1 = new Consumer(c, 1);
    p1.start(); 
    c1.start();
  }
}
class CubbyHole {
 private int contents;
 private boolean available = false;
 public synchronized int get() {
   while (available == false) {
      try {
        wait();
       }
       catch (InterruptedException e) {
       }
    }
    available = false;
    notifyAll();
    return contents;
 }
  public synchronized void put(int value) {
    while (available == true) {
     try {
        wait();
     }
     catch (InterruptedException e) { 
     } 
    }
    contents = value;
    available = true;
    notifyAll();
 }
}

class Consumer extends Thread {
   private CubbyHole cubbyhole;
   private int number;
   public Consumer(CubbyHole c, int number) {
    cubbyhole = c;
   this.number = number;
   }
  public void run() {
     int value = 0;
     for (int i = 0; i < 10; i++) {
        value = cubbyhole.get();
          System.out.println("Consumer #" + this.number+ " got: " + value);
   }
  }
  }

  class Producer extends Thread {
  private CubbyHole cubbyhole;
  private int number;

 public Producer(CubbyHole c, int number) {
 cubbyhole = c;
 this.number = number;
 }

 public void run() {
 for (int i = 0; i < 10; i++) {
   cubbyhole.put(i);
   System.out.println("Producer #" + this.number+ " put: " + i);
    try {
    sleep((int)(Math.random() * 100));
     } catch (InterruptedException e) { }
  }
 }
 }

诀窍是让生产者线程进入休眠状态,直到消费者完成消费之前的元素。在我提供的示例代码中,睡眠可以解决问题

...相同的效果可以通过一个很好的旧 while 循环来实现。

于 2013-09-17T12:43:35.783 回答
0

join()函数在许多编程语言(包括 Java)中的名称和函数中都很常见。它所做的只是让调用线程等待直到被调用者/子线程完成,ei。它一直等到子线程返回。

Thread t = new Thread() {
    public void run() {
        System.out.println("1");
        // Something that takes a long time to compute.
    }
 };
 t.start();
 t.join();
 System.out.println("2");

输出将是有序的。因为在 t 完成并返回之前不会到达最后一行。

于 2013-09-17T12:44:01.127 回答