先开题,有时间研究。
根据以往的经验,多线程同步最经常使用的是锁(WINCE的是递归锁)和条件变量。
java是从语法上支持多线程的,synchronized关键字可以应用于容器,方法和代码。
*锁
All objects automatically contain a single lock (also referred to as a monitor).
所有的java object都包含一个锁(或者称之为“监视器”),注意:这是一个递归锁。
There’s also a single lock per class (as part of the Class object for the class), so that synchronized static methods can lock each other out from simultaneous access of static data on a class-wide basis.
java的每一个Class也都有这样的一个锁。
为一个类的方法声明修饰synchronized,那么这个方法就使用这个实例的锁来和其它修饰了的方法进行synchronized。(如果是一个静态方法,就使用Class的锁)
It is imperative that the user manually synchronize on the returned collection when iterating over it:
Collection c = Collections.synchronizedCollection(myCollection); ... synchronized(c) { Iterator i = c.iterator(); // Must be in the synchronized block while (i.hasNext()) foo(i.next()); }
强烈建议用户在使用迭代器的时候手工进行同步!
另外一个线程对一个同步容器的连续多个操作,并不保证这个线程一直拥有这个锁。