gpt4 book ai didi

Java 多线程 CopyONWriteArrayList

转载 作者:行者123 更新时间:2023-11-30 06:48:55 25 4
gpt4 key购买 nike

我想使用可以被多线程代码不断访问的数据结构。请让我知道 java 中的任何数据结构,我可以在其中等待并使用通知选项。请看下面的代码,为什么CDRemove的run方法不打印所有值

public class ConcurrencyDemo {

public static void main(String[] args) throws InterruptedException {
CopyOnWriteArrayList<String> threadSafeList = new CopyOnWriteArrayList<String>();
CDInsert cd1 = new CDInsert(threadSafeList);
CDRemove cr1 = new CDRemove(threadSafeList);
cd1.start();

cr1.start();
}
}

class CDInsert extends Thread
{
List threadSafeList;

public CDInsert(List threadSafeList) {
this.threadSafeList = threadSafeList;
}

public void run()
{
int counter = 0;
while(counter < 20){
counter++;
threadSafeList.add(String.valueOf(counter));
System.out.println("Counter value is "+counter);
}
}

public void showItem(){
Iterator<String> failSafeIterator = threadSafeList.iterator();
while(failSafeIterator.hasNext()){
System.out.printf("Read from CopyOnWriteArrayList : %s %n", failSafeIterator.next());
}
}
}

class CDRemove extends Thread {
List threadSafeList;

public CDRemove(List threadSafeList) {
this.threadSafeList = threadSafeList;
}

public void run(){

Iterator<String> failSafeIterator = threadSafeList.iterator();
System.out.println("Fail Safe Iterator is "+failSafeIterator);
while(true){
System.out.println("Fail Safe Iterator is "+failSafeIterator);
while(failSafeIterator.hasNext()){
System.out.printf("Read from CopyOnWriteArrayList : %s %n", failSafeIterator.next());
}
}
}
}

最佳答案

线程CDRemove有一个无限循环:

 while(true){ // Change this.
while(failSafeIterator.hasNext()){
System.out.printf("Read from CopyOnWriteArrayList : %s %n", failSafeIterator.next());
}
}

现在迭代器将表示构造时列表的状态。如果 CDInsert 线程仍在运行,迭代器将不会拥有所有元素。

关于Java 多线程 CopyONWriteArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43192112/

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