Java Mulithreaded CopyONWriteArrayList

时间:2017-04-03 18:46:55

标签: java multithreading

我想使用多线程代码可以不断加入的数据结构。请让我知道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());
            }
        }
    }
} 

1 个答案:

答案 0 :(得分:1)

线程CDRemove有一个无限循环:

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

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