简体   繁体   中英

How to synchronize threads between methods?

I'm creating a queue with 10 items (at the BeforeClass), then i'm using 10 threads (using the @Test TestNG annotation with threads) to read the values from the queue. im using a while loop to make sure i'm not trying to poll values from empty queue. however, due to syncronization issue the while is asking for the state of the queue right before other thread is polling value and clear it, hence i'm getting null instead of stop polling from the queue. how can I sync between while loop to the queue?

import org.testng.annotations.Test;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedDeque;

public class LinkedConcurrentQueue {
    Queue<String> queue;

    @Test
    public void testA(){
        queue = new ConcurrentLinkedDeque<String> ();
        for(int i = 0; i<10; i++ ){
            queue.add(String.valueOf(i));
        }
    }

    @Test(enabled = true, threadPoolSize = 10, invocationCount = 10,  timeOut = 100000)
    public void testB() throws InterruptedException {
        while(!queue.isEmpty()) {
            Thread.sleep(20);
            System.out.println(queue.poll ( ));
        }
    }
}

the output in this case is:

1
0
3
4
2
8
7
6
5
9
null
null
null
null
null

You don't have to sync (because you're using a concurrent queue), but you do need to change the loop a bit:

while (true) {
    String el = queue.poll();
    if (el == null)
        break; // no more elements
    Thread.sleep(20);
    System.out.println(el);
}

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