为什么对obs的操作都加上了synchronized
/*
 * @(#)Observable.java 1.38 04/01/12
 *
 * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */package java.util;/**
 * This class represents an observable object, or "data"
 * in the model-view paradigm. It can be subclassed to represent an 
 * object that the application wants to have observed. 
 * <p>
 * An observable object can have one or more observers. An observer 
 * may be any object that implements interface <tt>Observer</tt>. After an 
 * observable instance changes, an application calling the 
 * <code>Observable</code>'s <code>notifyObservers</code> method  
 * causes all of its observers to be notified of the change by a call 
 * to their <code>update</code> method. 
 * <p>
 * The order in which notifications will be delivered is unspecified.  
 * The default implementation provided in the Observable class will
 * notify Observers in the order in which they registered interest, but 
 * subclasses may change this order, use no guaranteed order, deliver 
 * notifications on separate threads, or may guarantee that their
 * subclass follows this order, as they choose.
 * <p>
 * Note that this notification mechanism is has nothing to do with threads 
 * and is completely separate from the <tt>wait</tt> and <tt>notify</tt> 
 * mechanism of class <tt>Object</tt>.
 * <p>
 * When an observable object is newly created, its set of observers is 
 * empty. Two observers are considered the same if and only if the 
 * <tt>equals</tt> method returns true for them.
 *
 * @author  Chris Warth
 * @version 1.38, 01/12/04
 * @see     java.util.Observable#notifyObservers()
 * @see     java.util.Observable#notifyObservers(java.lang.Object)
 * @see     java.util.Observer
 * @see     java.util.Observer#update(java.util.Observable, java.lang.Object)
 * @since   JDK1.0
 */
public class Observable {
    private boolean changed = false;
    private Vector obs;
   
    /** Construct an Observable with zero Observers. */    public Observable() {
obs = new Vector();
    }    /**
     * Adds an observer to the set of observers for this object, provided 
     * that it is not the same as some observer already in the set. 
     * The order in which notifications will be delivered to multiple 
     * observers is not specified. See the class comment.
     *
     * @param   o   an observer to be added.
     * @throws NullPointerException   if the parameter o is null.
     */
    public synchronized void addObserver(Observer o) {
        if (o == null)
            throw new NullPointerException();
if (!obs.contains(o)) {
    obs.addElement(o);
}
    }    /**
     * Deletes an observer from the set of observers of this object. 
     * Passing <CODE>null</CODE> to this method will have no effect.
     * @param   o   the observer to be deleted.
     */
    public synchronized void deleteObserver(Observer o) {
        obs.removeElement(o);
    }    /**
     * If this object has changed, as indicated by the 
     * <code>hasChanged</code> method, then notify all of its observers 
     * and then call the <code>clearChanged</code> method to 
     * indicate that this object has no longer changed. 
     * <p>
     * Each observer has its <code>update</code> method called with two
     * arguments: this observable object and <code>null</code>. In other 
     * words, this method is equivalent to:
     * <blockquote><tt>
     * notifyObservers(null)</tt></blockquote>
     *
     * @see     java.util.Observable#clearChanged()
     * @see     java.util.Observable#hasChanged()
     * @see     java.util.Observer#update(java.util.Observable, java.lang.Object)
     */
    public void notifyObservers() {
notifyObservers(null);
    }    /**
     * If this object has changed, as indicated by the 
     * <code>hasChanged</code> method, then notify all of its observers 
     * and then call the <code>clearChanged</code> method to indicate 
     * that this object has no longer changed. 
     * <p>
     * Each observer has its <code>update</code> method called with two
     * arguments: this observable object and the <code>arg</code> argument.
     *
     * @param   arg   any object.
     * @see     java.util.Observable#clearChanged()
     * @see     java.util.Observable#hasChanged()
     * @see     java.util.Observer#update(java.util.Observable, java.lang.Object)
     */
    public void notifyObservers(Object arg) {
/*
         * a temporary array buffer, used as a snapshot of the state of
         * current Observers.
         */
        Object[] arrLocal; synchronized (this) {
    /* We don't want the Observer doing callbacks into
     * arbitrary code while holding its own Monitor.
     * The code where we extract each Observable from 
     * the Vector and store the state of the Observer
     * needs synchronization, but notifying observers
     * does not (should not).  The worst result of any 
     * potential race-condition here is that:
     * 1) a newly-added Observer will miss a
     *   notification in progress
     * 2) a recently unregistered Observer will be
     *   wrongly notified when it doesn't care
     */
    if (!changed)
                return;
            arrLocal = obs.toArray();
            clearChanged();
        }        for (int i = arrLocal.length-1; i>=0; i--)
            ((Observer)arrLocal[i]).update(this, arg);
    }    /**
     * Clears the observer list so that this object no longer has any observers.
     */
    public synchronized void deleteObservers() {
obs.removeAllElements();
    }    /**
     * Marks this <tt>Observable</tt> object as having been changed; the 
     * <tt>hasChanged</tt> method will now return <tt>true</tt>.
     */
    protected synchronized void setChanged() {
changed = true;
    }    /**
     * Indicates that this object has no longer changed, or that it has 
     * already notified all of its observers of its most recent change, 
     * so that the <tt>hasChanged</tt> method will now return <tt>false</tt>. 
     * This method is called automatically by the 
     * <code>notifyObservers</code> methods. 
     *
     * @see     java.util.Observable#notifyObservers()
     * @see     java.util.Observable#notifyObservers(java.lang.Object)
     */
    protected synchronized void clearChanged() {
changed = false;
    }    /**
     * Tests if this object has changed. 
     *
     * @return  <code>true</code> if and only if the <code>setChanged</code> 
     *          method has been called more recently than the 
     *          <code>clearChanged</code> method on this object; 
     *          <code>false</code> otherwise.
     * @see     java.util.Observable#clearChanged()
     * @see     java.util.Observable#setChanged()
     */
    public synchronized boolean hasChanged() {
return changed;
    }    /**
     * Returns the number of observers of this <tt>Observable</tt> object.
     *
     * @return  the number of observers of this object.
     */
    public synchronized int countObservers() {
return obs.size();
    }
}

解决方案 »

  1.   

    安装JDK是不是有选择是否安装源代码,安装好后,JDK目录有个src.zip 18.73MB
      

  2.   

    Vector本来就是线程安全的,仅仅obs.removeAllElements()这样的操作也要加上synchronized不是多此一举?
      

  3.   

    vector现在已经很少人用了,是不是?
      

  4.   

    vector是线程安全,但是Observable 不加就不是
      public synchronized void addObserver(Observer o) {
       
        }
        public synchronized void deleteObserver(Observer o) {
             
        }
    这2个方法是加锁的互斥的
      

  5.   

    我看了vector的api
    发现那些方法前面没synchronized
    可能你去看下vector源码可能找到答案
    这问题有点难
      

  6.   

         if (o == null)
                throw new NullPointerException();
        if (!obs.contains(o)) {
            obs.addElement(o);
        }
    这个并不是原子性的
    不加synchronized可能会乱
      

  7.   

        public boolean contains(Object elem) {
    return indexOf(elem, 0) >= 0;
        }
    这个无synchronized的
    我觉得
    可能是Observable的方法需要进行锁定排斥的
    高手快来啊
      

  8.   

    就是因为vector是线程安全的,所以在性能上没有其他的非线程安全的集合类高,毕竟大部分的应用程序是无需关注线程安全的。所以逐渐就没有人使用了。加上Executor框架的盛行,就更加没有人注意了
      

  9.   

    因为Vector是JAVA 2之前的遗留类。JAVA 2对类库进行了重大重构,新加入的集合类如ArrayList,HashMap等都不再是线程安全的,而是用Collections.SynchronizedXXX()系列方法来构造线程安全的集合。为了和老版本的代码兼容,Java保留了Vector的线程安全特性。
      

  10.   

    Vector是ArrayList的子类,二者唯一区别就是Vector是线程安全的。
    这有好处也有不好的。好处就是保证存取的数据不会出现不一致或者脏数据;不好的呢就是访问效率在多线程下会比ArrayList慢(因为引入了多线程)而ArrayList与Vector正好相反。用法:
    1)在多线程环境下用Vector即可,你无须担心并发问题;但ArrayList的话你就必须自己注意保证对ArrayList访问的线程安全性。当然,jdk的集合框架已经帮你搞定了,你无须自己实现,就在
    java.util.Collections.synchronizedList方法,返回一个线程安全的List
    对应的还有Set,Map等等。你可以找JDK文档,里面有很详细的用法2)在非多线程环境,建议不要用Vector,没有这个必要,而且会降低存取效率。直接用ArrayList即可一句话,Vector与ArrayList在线程安全上的特点,类似LinkedList(链表)和ArrayList(矩阵/数组)在插入数据与检索数据上的平衡一样。LinkedList插入数据快但检索没有ArrayList慢,反之亦然。所以,要结合你的具体应用场景来谈。
      

  11.   


    先好好去理解 锁synchronized 这个关键字真正含义,
    同步?避免脏数据?互斥? 搞的清清楚楚 就知道了 然后 去jdk里看看 这个 东东 static
    <T> Collection<T>
    synchronizedCollection(Collection<T> c)
              返回由指定 collection 支持的同步(线程安全的)collection。
    static
    <T> List<T>
    synchronizedList(List<T> list)
              返回由指定列表支持的同步(线程安全的)列表。
    static
    <K,V> Map<K,V>
    synchronizedMap(Map<K,V> m)
              返回由指定映射支持的同步(线程安全的)映射。
    static
    <T> Set<T>
    synchronizedSet(Set<T> s)
              返回由指定 set 支持的同步(线程安全的)set。
    static
    <K,V> SortedMap<K,V>
    synchronizedSortedMap(SortedMap<K,V> m)
              返回由指定有序映射支持的同步(线程安全的)有序映射。
    static
    <T> SortedSet<T>
    synchronizedSortedSet(SortedSet<T> s) 
      

  12.   

    请注意notifyObservers()里面synchronized块。
    为了不把上了锁的Observable传到Observer.update()里面去,程序首先在synchronized块里面做了个snapshot(arrLocal)。
    而且那些deleteObservers()函数的synchronize是Observable自己,而非Observable.obs.Hope I express it clearly.
      

  13.   

    谢谢你的答复,前面的说的很有道理,我想问下:deleteObservers()函数前面加不加synchronize对程序处理并发上会有影响吗
      

  14.   

    问题已解决,答案请参照
    http://blog.csdn.net/super254/archive/2009/12/22/5055507.aspx
    谢谢大家参与