omg,打了半天忘了存盤了,運(yùn)行Java程序時(shí)一個(gè)crash死機(jī)了。。。
直接把今天看的部分放上來了
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 域
現(xiàn)在的處理器和編譯器很有可能產(chǎn)生一些同步時(shí)的錯(cuò)誤:
~ 多處理器的計(jì)算機(jī)會臨時(shí)地在寄存器或緩存中存放數(shù)據(jù),因此在不同處理器上運(yùn)行的線程可能會從同一個(gè)內(nèi)存區(qū)域獲得不同的值。
~ 編譯器為了提高效率,會重新排列指令順序。但它們在操作時(shí)假設(shè)只有當(dāng)有明確的更改指令時(shí),內(nèi)存數(shù)據(jù)才會改變。然而,實(shí)際上該數(shù)據(jù)有可能被另一線程修改。
Brian Goetz指出了應(yīng)該何時(shí)使用同步:當(dāng)你更改了某個(gè)下次可能會被其他線程訪問的變量,或者訪問了一個(gè)上一次可能被其他線程修改的變量,你就必須使用synchronization。
volatile關(guān)鍵字提供了一種同步實(shí)例域的訪問的機(jī)制。如果把某一字段聲明為volatile,編譯器和虛擬機(jī)就會考慮到該數(shù)據(jù)域可能會同時(shí)被另一線程訪問。
例如,boolean值的字段done可能被一個(gè)線程修改,并由另一個(gè)線程訪問。有兩種方法實(shí)現(xiàn):
1)
public synchronized boolean isDone() {return done;}
private boolean done;
這種方法有一個(gè)潛在的缺陷:如果另一個(gè)方法鎖住了對象,isDone方法可能會停滯。
2)
public boolean isDone() {return done;}
private volatile boolean done;
當(dāng)然,訪問一個(gè)volatile字段會比訪問普通字段慢一些。
總結(jié)一下,對某字段的并發(fā)訪問在以下情況中是安全的:
~ volatile字段
~ final字段,并且在構(gòu)造器完成后就被修改。
~ 訪問操作被鎖保護(hù)
5. 鎖死 Deadlocks
死鎖的幾種情況:(以銀行轉(zhuǎn)帳為例)
1)帳號1: $2,000 帳號2: $3,000
先試圖從帳號1轉(zhuǎn)3000到帳號2,再試圖從帳號2轉(zhuǎn)4000到帳號1。
容易得出,最后兩個(gè)線程都會鎖死。
2)有許多帳號,其中
帳號1: $1,990 其余帳號都是 $990
線程1: 從帳號1轉(zhuǎn)$995到帳號2
其余線程: 從自己的帳號轉(zhuǎn)出$995到其他帳號
顯然,除了線程1,其余線程都被停滯。
線程1操作后,帳號1剩$995,帳號2剩$1,985,此時(shí)線程1使用signal方法隨機(jī)恢復(fù)了一個(gè)線程,假設(shè)是線程3,但恢復(fù)后發(fā)現(xiàn)帳號3的資金仍不夠轉(zhuǎn)帳,于是繼續(xù)停滯。
假設(shè)此時(shí)線程1又執(zhí)行了從帳號1轉(zhuǎn)出$997的指令,于是線程1也停滯。
系統(tǒng)鎖死。
罪魁禍?zhǔn)拙褪莝ignal方法。