没有输出程序

时间:2015-02-01 15:10:32

标签: java

我正在编写一个小程序来创建4个线程来完成4个任务:增加列表中每个元素的值,减少奇数元素的值并打印输出,每20毫秒删除列表中的最后一个元素,添加元素到列表每20毫秒,但线程2不显示输出

public class MyClass {
    static volatile ArrayList<Integer> list = new ArrayList<Integer>();

    public static void main(String[] args) {

    Thread th1 = new Thread() {
        public void run() {
            synchronized (list) {
                while (true) {
                    if (list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            list.set(i, list.get(i) + 1);
                        }
                    }
                }
            }
        }
    };

    Thread th2 = new Thread() {
        public void run() {
            while (true) {
                synchronized (list) {
                    if (list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            if ((list.get(i) % 2) != 0) {
                                list.set(i, list.get(i) - 1);
                                System.out.println(list.get(i));
                            }
                        }
                    }
                }
            }
        }
    };

    Thread th3 = new Thread() {
        public void run() {
            while (true) {
                synchronized (list) {
                    if (list.size() > 0) {
                        list.remove(list.size() - 1);
                    }
                }
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    Thread th4 = new Thread() {
        public void run() {
            for (int i = 0;; i++) {
                synchronized (list) {
                    list.add(i);
                }
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    th4.start();
    th2.start();
    th1.start();
    th3.start();        
}
}

我的代码有什么问题吗?

1 个答案:

答案 0 :(得分:2)

第一个线程锁定列表,然后进入无限循环。所以第二个永远不能锁定列表并完成它的工作,因为第一个线程永远持有锁。