以上内容均来自于本书和我的自己理解的总结
Java Threads, 3rd Edition [Book] (oreilly.com)
synchronized |
The Java specification provides certain mechanisms that deal specifically with this problem. The Java language provides the synchronized keyword; in comparison with other threading systems, this keyword allows the programmer access to a resource that is very similar to a mutex lock. For our purposes, it simply prevents two or more threads from calling the methods of the same object at the same time
Java规范提供了特定的机制来专门处理这个问题。Java语言提供了synchronized关键字;与其他线程系统相比,该关键字允许程序员访问非常类似于互斥锁的资源。出于我们的目的,它只是防止两个或多个线程同时调用同一对象的方法
|
If thread1 wants to call synchronized method. while another thread2 is already executing it, the thread1 must wait: the thread1 gets to complete execution of its method before the thread2 can execute its method. Since only one thread gets to call the synchronized method at a time, only one thread at a time accesses the data
如果thread1想要调用synchronized方法。当另一个thread2已经在执行它时,thread1必须等待:thread1在thread2可以执行其方法之前完成其方法的执行。因为一次只有一个线程可以调用synchronized方法,所以一次只有一个线程访问数据
Under the covers, the concept of synchronization is simple: when a method is declared synchronized, the thread that wants to execute the method must acquire a token, which we call a lock. Once the method has acquired (or checked out or grabbed) this lock, it executes the method and releases (or returns) the lock. No matter how the method returns—including via an exception—the lock is released. There is only one lock per object, so if two separate threads try to call synchronized methods of the same object, only one can execute the method immediately; the other has to wait until the first thread releases the lock before it can execute the method.
实际上,同步的概念很简单:当一个方法被声明为已同步时,想要执行该方法的线程必须获取一个令牌,我们称之为锁。一旦该方法获得(或签出或抓取)该锁,它就会执行该方法并释放(或返回)锁。无论该方法如何返回,包括通过异常返回,锁都会被释放。每个对象只有一个锁,因此如果两个单独的线程试图调用同一对象的同步方法,则只有一个线程可以立即执行该方法;另一个线程必须等到第一个线程释放锁后才能执行该方法。
The scope of a lock is defined as the period of time between when the lock is grabbed and released. we have used only synchronized methods; this means that the scope of these locks is the period of time it takes to execute the methods. This is referred to as method scope. we'll examine locks that apply to any block of code inside a method or that can be explicitly grabbed and released; these locks have a different scope. We'll examine this concept of scope as locks of various types are introduced. |
锁的范围定义为抓取锁和释放锁之间的时间段。我们只使用了同步方法;这意味着这些锁的作用域是执行方法所需的时间。这被称为方法范围。
我们将研究应用于方法内任何代码块的锁,或者可以显式地抓取和释放的锁;这些锁的作用域不同。随着各种类型锁的引入,我们将研究范围的这个概念。