Synchronize queues in Java on multiple threads

I understand the concept of synchronization, but now I'm sure why it's implemented in this way, so I need a little help:

I have 2 posts:

Periodicalthread will periodically receive data (assuming every 5 seconds) and put it in the queue (currently using arraydeque, but I don't know if any other queue implementation would be better)

Proccessthread will constantly check the queue to see if it is empty If it is not empty, it will process data (FIFO)

So, at first, my implementation will be:

// Both threads are inner class so they have access to Queue

private Queue queue;
private boolean isReadyToProccess;


class PeriodicalThread extends Thread {
    public void run() {
        while(true) {
           if(isNewDataAvailable) {
                // create Data object
                queue.add(data);
           }
        }
    }
}

class ProcessThread extends Thread {
    public void run() {
        while(true) {
           if(!queue.isEmpty() && isReadyToProccess) {
               Data data = queue.poll();
               processData(data);
           }
        }
    }
}

private void processData(Data data) {
    // this method send data over network,and the server response callback
    // changes isReadyToProcess value to true.
}

Then, when I want to handle synchronization, I don't know whether I should use a lock object (and how it is implemented), or whether a thread safe package queue implementation already exists (because of the add () and poll () methods)

Edit: I forgot that the isreadytoprocess flag indicates that the next queue data object is... OK, ready for processing This flag should also be synchronized

Solution

Arraydeque does not support concurrency Instead, use real queues that support concurrent work, such as BlockingQueue and its application in Java util. An implementation in the concurrent package I recommend using linkedblockingqueue

If you need to share flags between threads, it's best to use atomic Boolean instead of manually synchronizing basic Boolean fields

Note: if you are going to use concurrent processes, it is best to use Java. Net, which supports locking and synchronization out of the box util. Classes provided by the concurrent package

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>