简体   繁体   中英

Blocking async queues Java

I'm trying to figure out a way to implement the following in Java.

Thread1 will add jobs to queue1. Another different thread (Thread2) will add jobs to queue2.

In the run() method of Thread1 I wait until there's a job in queue 1, and let's say I will print it, if and only if there are no awaiting jobs in queue2.

How may I notify Thread1 that Thread2 has added a job in queue2? Here is Thread1 Class

public class Thread1 implements Runnable {
private List queue1 = new LinkedList();

public void processData(byte [] data, int count) {
    byte[] dataCopy = new byte[count];
    System.arraycopy(data, 0, dataCopy, 0, count);
    synchronized(queue1) {
        queue1.add(data);
        queue1.notify();
    }
}

public void run() {
    byte [] data;

    while(true) {
        // Wait for data to become available
        synchronized(queue1) {
            while(queue1.isEmpty()) {
                try {
                    queue1.wait();
                } catch (InterruptedException e) {}
            }
            data = (byte[]) queue1.remove(0);
        }
        // print data only if queue2 has no awaiting jobs in it
    }
}

You have not quite well explained your question and I am not sure what you are trying to ask -its very confusing to read what you have written. Also, I don't see any code for Thread-2 and Queue-2 .

So I am going to put general advice,

1. Use existing implementation of Blocking Queue instead of doing private List queue1 = new LinkedList(); and then doing synchronized(queue1) .

Here is documentation of BlockingQueue interface. You can use class , LinkedBlockingQueue as implementation.

2. Sample code - If you browse above link of BlockingQueue documentation, you see code at the bottom highlighting as how to write consumers and producers. There you don't see instance of queue getting created inside Thread class but set via constructor - that way you can share a single queue with as many threads as you like - by passing reference to queue in Runnable constructor.

3. BlockingQueue implementations are thread-safe - so you don't have to synchronize on queue instances. You can freely pass queue instances to as many threads as you like believing that its methods will be called in synchronized way.

So I suggest that you try to rewrite whatever program you are trying to write using above construct and code samples and come back for any more questions.

Hope it helps !!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM