omg,打了半天忘了存盤了,運行Java程序時一個crash死機了。。。
直接把今天看的部分放上來了
1. The synchronized Keyword
Before the Lock and Condition interfaces were added to JDK 5.0, the Java language used a different concurrency mechanism. Ever since version 1.0, every object in Java has an implicit lock. If a method is declared with the synchronized keyword, then the object's lock protects the entire method. That is, to call the method, a thread must acquire the object lock.
In other words,
public synchronized void method()
{
method body
}
is the equivalent of
public void method()
{
implicitLock.lock();
try
{
method body
}
finally { implicitLock.unlock(); }
}
For example, instead of using an explicit lock, we can simply declare the transfer method of the Bank class as synchronized.
The implicit object lock has a single associated condition. The wait method adds a thread to the wait set, and the notifyAll/notify methods unblock waiting threads. In other words, calling wait or notifyAll is the equivalent of
implicitCondition.await();
implicitCondition.signalAll();
However, the implicit locks and conditions have some limitations. Among them are:
You cannot interrupt a thread that is trying to acquire a lock.
You cannot specify a timeout when trying to acquire a lock.
Having a single condition per lock can be inefficient.
The virtual machine locking primitives do not map well to the most efficient locking mechanisms available in hardware.
What should you use in your codeLock and Condition objects or synchronized methods? Here is our recommendation:
1)It is best to use neither Lock/Condition nor the synchronized keyword. In many situations, you can use one of the mechanisms of the java.util.concurrent package that do all the locking for you. For example, on page 48, you will see how to use a blocking queue to synchronize threads that work on a common task.
2)If the synchronized keyword works for your situation, by all means, use it. You write less code and have less room for error. Example 1-5 shows the bank example, implemented with synchronized methods.
3)Use Lock/Condition if you specifically need the additional power that these constructs give you.
Note: At least for now, using the synchronized keyword has an added benefit. Tools that monitor the virtual machine can report on the implicit locks and conditions, which is helpful for debugging deadlock problems. It will take some time for these tools to be extended to the java.util.concurrent mechanisms.
2. Monitors
The locks and conditions are powerful tools for thread synchronization, but they are not very object oriented. For many years, researchers have looked for ways to make multithreading safe without forcing programmers to think about explicit locks. One of the most successful solutions is the monitor concept that was pioneered by Per Brinch Hansen and Tony Hoare in the 1970s. In the terminology of Java, a monitor has these properties:
~ A monitor is a class with only private fields.
~ Each object of that class has an associated lock.
~ All methods are locked by that lock. In other words, if a client calls obj.method(), then the lock for obj is automatically acquired at the beginning of the method call and relinquished when the method returns. Because all fields are private, this arrangement ensures that no thread can access the fields while another thread manipulates them.
~ The lock can have any number of associated conditions.
However, a Java object differs from a monitor in three ways:
~ Fields are not required to be private.
~ Methods are not required to be synchronized.
~ The lock has only one condition.
This disrespect for security enraged Per Brinch Hansen. In a scathing review of the multithreading primitives in Java, he wrote: "It is astounding to me that Java's insecure parallelism is taken seriously by the programming community, a quarter of a century after the invention of monitors and Concurrent Pascal. It has no merit." [Java's Insecure Parallelism, ACM SIGPLAN Notices 34:3845, April 1999]
3. Synchronized Blocks
Recall that each object has a lock. A thread can acquire the lock in one of two ways, by calling a synchronized method or by entering a synchronized block. If the thread calls obj.method(), it acquires the lock for obj. Similarly, if a thread enters a block of the form
synchronized (obj) // this is the syntax for a synchronized block
{
critical section
}
then the thread acquires the lock for obj. The lock is reentrant. If a thread has acquired the lock, it can acquire it again, incrementing the hold count. In particular, a synchronized method can call other synchronized methods with the same implicit parameter without having to wait for the lock.
It is legal to declare static methods as synchronized. If such a method is called, it acquires the lock of the associated class object. For example, if the Bank class has a static synchronized method, then the lock of the Bank.class object is locked when it is called.
4. Volatile 域
現在的處理器和編譯器很有可能產生一些同步時的錯誤:
~ 多處理器的計算機會臨時地在寄存器或緩存中存放數據,因此在不同處理器上運行的線程可能會從同一個內存區域獲得不同的值。
~ 編譯器為了提高效率,會重新排列指令順序。但它們在操作時假設只有當有明確的更改指令時,內存數據才會改變。然而,實際上該數據有可能被另一線程修改。
Brian Goetz指出了應該何時使用同步:當你更改了某個下次可能會被其他線程訪問的變量,或者訪問了一個上一次可能被其他線程修改的變量,你就必須使用synchronization。
volatile關鍵字提供了一種同步實例域的訪問的機制。如果把某一字段聲明為volatile,編譯器和虛擬機就會考慮到該數據域可能會同時被另一線程訪問。
例如,boolean值的字段done可能被一個線程修改,并由另一個線程訪問。有兩種方法實現:
1)
public synchronized boolean isDone() {return done;}
private boolean done;
這種方法有一個潛在的缺陷:如果另一個方法鎖住了對象,isDone方法可能會停滯。
2)
public boolean isDone() {return done;}
private volatile boolean done;
當然,訪問一個volatile字段會比訪問普通字段慢一些。
總結一下,對某字段的并發訪問在以下情況中是安全的:
~ volatile字段
~ final字段,并且在構造器完成后就被修改。
~ 訪問操作被鎖保護
5. 鎖死 Deadlocks
死鎖的幾種情況:(以銀行轉帳為例)
1)帳號1: $2,000 帳號2: $3,000
先試圖從帳號1轉3000到帳號2,再試圖從帳號2轉4000到帳號1。
容易得出,最后兩個線程都會鎖死。
2)有許多帳號,其中
帳號1: $1,990 其余帳號都是 $990
線程1: 從帳號1轉$995到帳號2
其余線程: 從自己的帳號轉出$995到其他帳號
顯然,除了線程1,其余線程都被停滯。
線程1操作后,帳號1剩$995,帳號2剩$1,985,此時線程1使用signal方法隨機恢復了一個線程,假設是線程3,但恢復后發現帳號3的資金仍不夠轉帳,于是繼續停滯。
假設此時線程1又執行了從帳號1轉出$997的指令,于是線程1也停滯。
系統鎖死。
罪魁禍首就是signal方法。