简体   繁体   English

如何在方法之间同步线程?

[英]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. 我正在创建一个包含10个项目的队列(在BeforeClass上),然后使用10个线程(将@Test TestNG批注与线程一起使用)从队列中读取值。 im using a while loop to make sure i'm not trying to poll values from empty queue. 即时通讯使用while循环,以确保我没有尝试从空队列中轮询值。 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. 但是,由于同步化问题,while在其他线程轮询值并将其清除之前,一会儿请求队列的状态,因此我得到的是空值,而不是从队列中停止轮询。 how can I sync between while loop to the queue? 如何在while循环和队列之间进行同步?

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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