线程的使用,主要在于一个进程中多个线程的协同
工作,所以线程的同步就很重要。 线程的同步用于线程共享数据,转换和控制线程的执行,保证内存的一致性。
在 Java 中,运行环境使用程序(Monitor)来解决线程同步的问题。管程是一种并发同步 机制,它包括用于分配一个特定的共享资源或一组共享资源的数据和方法.
Java 为每一个拥有 synchronized 方法的对象实例提供了一个唯一的管程 为了完成分 。 配资源的功能,线程必须调用管程入口。管程入口就是 synchronized 方法入口。当调用同步 (synchronized)方法时,该线程就获得了该管程。
管程边界上实行严格的互斥,在同一时刻,只允许一个线程进入管程;当管程中已有了 一个线程时,其它希望进入管程的线程必须等待,这种等待是由管程自动管理的。
如果调用管程入口的线程发现资源已被分配,管程中的这个线程将调用等待操作 wait()。进入 wait()后,该线程放弃占用管程,在管程外面等待,以便其它线程进入管程。
最终,占用资源的线程将调用一个管程的入口把资源归还给系统,此时,该线程需调用 一个通知操作 notify(),通知
系统允许其中一个等待的线程获得管程并得到资源。被通知的 线程是排队的,从而避免无限拖延。
在 Java.lang 中提供了用来编写管程的两个方法:notify()和 wait()。此外还有 notifyAll(),它通知所有等待的线程,使它们竞争管程,结果是其中一个获得管程,其佘返回 等待状态。
Java Object's monitor , owner of monitor &; synchronized &; Object's wait(), notify() and not2006-09-06 20:41 Java associates a monitor with each object. The monitor enforces mutual exclusive access to synchronized methods invoked on the associated object. When a thread calls a synchronized method on an object, the JVM checks the monitor for that object
java 使用管程机制将各个对象联系到一起。管程的进入是互斥的。当一个带有 同步方法对象的线程申请进入管程,JVM 会对该对象进行监控。
If the monitor is unowned, ownership is assigned to the calling thread, which is then allowed to proceed with the method call 如果在一个线程被许可进入管程时,管程没有被占用,那么管程的所有权将会分 配给该线程。
if the monitor is owned by another thread, the calling thread will be put on hold until the monitor becomes available 如果管程已经被其他线程占用了, 那么这个线程将被放入等待线程的队列直到管 程可用。
When a thread exits a synchronized method, it releases the monitor, allowing a waiting thread (if any) to proceed with its synchronized method call. 当一个线程结束了同步的方法,将会释放管程所有权,将会使某个 waiting 的带 有同步方法的线程运行起来。 Note that
Java monitors are not like tradition
al critical sections. 值 得注意的是 java 的管程是没有所谓信号量的。 Declaring a method synchronized does not imply that only one thread may execute that method at a time, as would be the case with a critical section. 声明一个同步的方法并不意 味着为了达到信号量同样的效果,每一次只有一个线程能够执行该方法。It implies that only one thread may invoke that method (or any synchronized method) on a particular object at any given time. 那意味着在给定的任意 时间里,只有一个线程能够调用一个具体的对象上的某方法。Java monitors are associated with objects, not with blocks of code. java 的管程是依靠对 象们互相关联的,而不是代码块。Two threads may concurrently execute the same synchronized method, provided that the method is invoked on different objects (that is, a.method() and b.method(), where a != b).两个线程可 以并发运行同一个同步的方法