线程上的迭代器CopyOnWriteArrayList不工作​​

时间:2016-03-17 21:35:49

标签: java eclipse multithreading iterator copyonwritearraylist

我正在为OCP考试做一些练习。目前,当我使用多个帖子时,我尝试打印 CopyOnWriteArrayList内容。根据文档,CopyOnWriteArrayList的迭代器将

  

打印列表中的数字,这些数字是在创建迭代器时出现的

因此,当从CopyOnWriteArrayList开始一个线程写而从CopyOnWriteArrayList开始另一个读时,我希望(有时)打印出一些项目。在完成写入线程之后遍历CopyOnWriteArrayList 时,我希望 new iterator 打印出所有项目

不幸的是,当使用匿名实施的Runnable接口时,不起作用。但它在使用自定义线程类时起作用,我在其中传递对CopyOnWriteArrayList的引用。

现在,我不明白为什么会这样。我不确定final CopyOnWriteArrayList<Integer> intList = new CopyOnWriteArrayList<>();是否会导致这种影响 - 如果是这样的话 - 我根本不知道为什么会这样做?

对此主题的任何意见都表示赞赏!

使用Runnable的匿名实现 - 无法按预期工作

static void copyOnWriteCollections() {
    System.out.println("copyOnWriteCollections".toUpperCase());

    final CopyOnWriteArrayList<Integer> intList = new CopyOnWriteArrayList<>();

    Thread tADD = new Thread(new Runnable() {
        public void run() {
            for (int i = 0; i < 10000; i++) {
                intList.add(i);
            }
        }
    });
    tADD.start();

    /// will print the numbers in the list which are present
    /// at the moment the iterator is created
    Thread tREAD = new Thread(new Runnable() {
        public void run() {
            for (Integer i : intList) {
                System.out.print(i);
                System.out.print(" ");
            }
        }
    });     
    tREAD.start();

    try {
        tADD.join();
        tREAD.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // will print out all numbers - as iterator is created when all
    // modifications
    // to intList have finished
    System.out.println();
    new Thread(new Runnable() {
        public void run() {
            System.out.println("new");
            System.out.println("\tsize of intList: " + intList.size());

            Iterator<Integer> it = intList.iterator();

            while (it.hasNext()) {
                int i = it.next();
                System.out.print(i);
                System.out.print(" ");
            }

            System.out.println("end");
        }
    }).start();
}

输出(有时 - 因为有线程) first read thread prints out some numbers, second read thread won't print out any numbers!

使用自定义线程类 - 按预期工作

class CopyOnWriteThread extends Thread {

    Iterator<Integer> it = null;
    boolean read = false;
    CopyOnWriteArrayList<Integer> intList = null;

    public CopyOnWriteThread(CopyOnWriteArrayList<Integer> intList, boolean read) {
        this.intList = intList;
        this.read = read;
    }

    public void run() {
        if (read) {
            it = intList.iterator();

            System.out.println("START read (" + Thread.currentThread().getName() + ")");
            System.out.print("\t");
            while (it.hasNext()) {
                System.out.print(it.next());
                System.out.print(" ");
            }
            System.out.println();
            System.out.println("END read (" + Thread.currentThread().getName() + ")");
        } else {
            System.out.println("START write (" + Thread.currentThread().getName() + ")");
            for (int i = 0; i < 10000; i++) {
                intList.add(i);
            }
            System.out.println("END write (" + Thread.currentThread().getName() + ")");
        }
    }
}

static void copyOnWriteCollections_CustomThread() {
    CopyOnWriteArrayList<Integer> intList = new CopyOnWriteArrayList<>();

    CopyOnWriteThread tWRITE = new CopyOnWriteThread(intList, false);
    CopyOnWriteThread tREAD = new CopyOnWriteThread(intList, true);
    tWRITE.start();
    tREAD.start();

    try {
        tWRITE.join();
        tREAD.join();
    } catch (InterruptedException e) {
    }

    CopyOnWriteThread tREAD2 = new CopyOnWriteThread(intList, true);
    tREAD2.start();
}

输出 - 按预期工作 first read thread prints out some numbers, second read thread prints out all numbers

目前我正在开发一台 Win10机器,JDK 1.7.0_25和Eclipse Mars Release 4.5.0

1 个答案:

答案 0 :(得分:0)

正如@ user2357112发布的那样,代码没有任何问题。问题似乎是 Eclipse相关

在Eclipse Mars / JRE 1.7.0_25中运行问题代码时,它不会打印出0到9999之间的数字。相反,它会立即退出,就像没有新的迭代器一样。< / p>

我从命令行编译代码并使用java.exejavaw.exe启动它。两者都显示正确的输出。

java命令

java -classpath "c:\Chapter14\ConcurrentCollections\bin" concurrentCollections.TestClass

<强>结果

Command line output - relevant pieces

javaw命令

javaw -classpath "c:\Chapter14\ConcurrentCollections\bin" concurrentCollections.TestClass > "c:\test.txt"

<强>结果

test file contents - first xxx numbers - contains all numbers

现在我可以说(当然)我的代码和JVM没有任何问题!

修改

我通过修改运行配置将输出重定向到文件。在eclipse中重启了应用程序。 Output.txt包含所有数字 - 但在Eclipse中的控制台窗口(分配控制台)中,数字不会出现...

Run Configurations Eclipse