通过代码链进行同步

时间:2015-01-19 05:14:42

标签: java synchronization

有人可以告诉我,如果在“myClass”中执行run命令的Java线程(在下面的代码中)在CustomList的get()命令获取它的时间和myClass运行请求的时间之间丢失对象的同步同一个对象的同步?

如果初始线程保持同步,那么CustomList的get命令创建的“myThread”的中心代码永远不能触发,直到原始线程完成所请求的Object。

public class myClass implements Runnable {

    private CustomList list;

    public myClass(){
        list = new CustomList();
        //Code to pack "list" goes here.
    }

    public void run(){
        int position = 0;
        while(position<list.size()){
            synchronized(list.get(position)){
                //Opperation's central code.
            }
            position++;
        }
    }

    public class CustomList extends ArrayList<Object> {

        public CustomList(){
            super();
        }

        public Object get(int i){
            Object o = super.get(i);
            synchronized(o){
                myThread thread = new myThread(o);
                thread.start();
                return o;
            }
        }

    }

    public class myThread extends Thread {

        private Object subject;

        public myThread(Object o){
            subject = o;
        }

        public void run(){
            synchronized(subject){
                //Do something to "subject"
                //BUT only AFTER the original Thread is finished with it.
            }
        }

    }

}

1 个答案:

答案 0 :(得分:3)

答案是肯定的。根据您提供的代码,您的CustomList不是线程安全的。

要解决此问题,请停止尝试自定义同步。你还不太了解它。而是使用java.util.Collections.synchronizedList()来包装java.util.ArrayList的实例。

private List<Object> list = Collections.synchronizedList(new ArrayList<Object>());