gpt4 book ai didi

java - 线程与单锁不同步

转载 作者:行者123 更新时间:2023-12-01 19:43:20 25 4
gpt4 key购买 nike

我无法正确同步该程序,第二个 println 中的结果也应该为 0,因为两个线程各创建和弹出 10000 次。我必须以不同的方式同步吗?

import java.util.*;

public class Main00 {

Queue<Integer> q = new PriorityQueue<Integer>();
Random rand = new Random();

public static void main(String[] args) {
new Main00().doStuff();
}

public void doStuff(){
Thread t1=new Thread(new Runnable(){
public void run(){
for(int i=0;i<10000;i++)produce();
}
});
Thread t2=new Thread(new Runnable(){
public void run(){
for(int i=0;i<10000;i++)consume();
}
});

System.out.println("Starting threads, q size is : "+q.size());
t1.start();
t2.start();

try{
t1.join();
t1.join();
}catch(InterruptedException e){}

System.out.println("Ending threads, q size is : "+q.size());
}

synchronized public void produce() {
q.add(rand.nextInt(100));
}

synchronized public void consume() {
q.poll();
}

}

最佳答案

您没有加入第二个线程:

    t1.join();
t1.join();

应该是:

    t1.join();
t2.join();

您还使用 poll不会阻塞:

Retrieves and removes the head of this queue, or returns null if this queue is empty.

您可能想使用PriorityBlockingQueue :

Multiple threads should not access a PriorityQueue instance concurrently if any of the threads modifies the queue. Instead, use the thread-safe PriorityBlockingQueue class.

您可以使用take避免方法busy-wait :

Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

关于java - 线程与单锁不同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31235085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com