接觸多線程已經(jīng)不少時間了,也做了不少事情,但是一直覺得用起來不那么順手,在debug的時候,往往會比較擔(dān)心在同步上出什么問題,想起"程序員最怕的是自己寫的代碼"這句話,覺得真是不假.
終于有一天,我覺得是時候把這個問題弄清楚了,所以,我就在網(wǎng)上找相關(guān)的內(nèi)容看,結(jié)果竟然是找不到在我這個階段應(yīng)該看的,不是太簡單,就是一筆帶過,不知所云.
廢了九牛二虎之力,終于差不多弄清楚了,其中有不少誤區(qū),以前認(rèn)為的和真理相差甚大.想起自己花費(fèi)的時間,真是覺得有點(diǎn)多,所以把它寫出來,一是防止自己以后又會忘掉,二是給像我一樣的似懂非懂者留下一點(diǎn)可以參考的東東.
閑話少說,轉(zhuǎn)入正題!
---------------------------------
先從線程的創(chuàng)建說起.線程的創(chuàng)建一共有兩種形式:
---------------------------------
一種是繼承自Thread類.Thread 類是一個具體的類,即不是抽象類,該類封裝了線程的行為。要創(chuàng)建一個線程,程序員必須創(chuàng)建一個從 Thread 類導(dǎo)出的新類。程序員通過覆蓋 Thread 的 run() 函數(shù)來完成有用的工作。用戶并不直接調(diào)用此函數(shù);而是通過調(diào)用 Thread 的 start() 函數(shù),該函數(shù)再調(diào)用 run()。
例如:
public class Test extends Thread{
public Test(){
}
public static void main(String args[]){
Test t1 = new Test();
Test t2 = new Test();
t1.start();
t2.start();
}
public void run(){
//do thread's things
}
}
----------------------------
另一種是實(shí)現(xiàn)Runnable接口,此接口只有一個函數(shù),run(),此函數(shù)必須由實(shí)現(xiàn)了此接口的類實(shí)現(xiàn)。
例如: public class Test implements Runnable{
Thread thread1;
Thread thread2;
public Test(){
thread1 = new Thread(this,"1");
thread2 = new Thread(this,"2");
}
public static void main(String args[]){
Test t = new Test();
t.startThreads();
}
public void run(){
//do thread's things
}
public void startThreads(){
thread1.start();
thread2.start();
}
}
兩種創(chuàng)建方式差別不大,第一種因?yàn)槔^承自Thread,只創(chuàng)建了自身對象,第二種還得創(chuàng)建Thread對象.但是當(dāng)你想繼承某一其它類時,你只能用后一種方式.大多數(shù)人偏愛后一種的原因大概也在于此吧.
-------------------------
下面我們來講synchronized的4種用法吧:
1.方法聲明時使用,放在范圍操作符(public等)之后,返回類型聲明(void等)之前.這時,線程獲得的是成員鎖,即一次只能有一個線程進(jìn)入該方法,其他線程要想在此時調(diào)用該方法,只能排隊(duì)等候,當(dāng)前線程(就是在synchronized方法內(nèi)部的線程)執(zhí)行完該方法后,別的線程才能進(jìn)入.
例如:
public synchronized void synMethod() {
//方法體
}
2.對某一代碼塊使用,synchronized后跟括號,括號里是變量,這樣,一次只有一個線程進(jìn)入該代碼塊.此時,線程獲得的是成員鎖.例如:
public int synMethod(int a1){
synchronized(a1) {
//一次只能有一個線程進(jìn)入
}
}
3.synchronized后面括號里是一對象,此時,線程獲得的是對象鎖.例如:
public class MyThread implements Runnable {
public static void main(String args[]) {
MyThread mt = new MyThread();
Thread t1 = new Thread(mt, "t1");
Thread t2 = new Thread(mt, "t2");
Thread t3 = new Thread(mt, "t3");
Thread t4 = new Thread(mt, "t4");
Thread t5 = new Thread(mt, "t5");
Thread t6 = new Thread(mt, "t6");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
}
public void run() {
synchronized (this) {
System.out.println(Thread.currentThread().getName());
}
}
}
對于3,如果線程進(jìn)入,則得到當(dāng)前對象鎖,那么別的線程在該類所有對象上的任何操作都不能進(jìn)行.在對象級使用鎖通常是一種比較粗糙的方法。為什么要將整個對象都上鎖,而不允許其他線程短暫地使用對象中其他同步方法來訪問共享資源?如果一個對象擁有多個資源,就不需要只為了讓一個線程使用其中一部分資源,就將所有線程都鎖在外面。由于每個對象都有鎖,可以如下所示使用虛擬對象來上鎖:class FineGrainLock {
MyMemberClass x, y;
Object xlock = new Object(), ylock = new Object();
public void foo() {
synchronized(xlock) {
//access x here
}
//do something here - but don't use shared resources
synchronized(ylock) {
//access y here
}
}
public void bar() {
synchronized(this) {
//access both x and y here
}
//do something here - but don't use shared resources
}
}
4.synchronized后面括號里是類,此時,線程獲得的是對象鎖.例如:
class ArrayWithLockOrder{
private static long num_locks = 0;
private long lock_order;
private int[] arr;
public ArrayWithLockOrder(int[] a)
{
arr = a;
synchronized(ArrayWithLockOrder.class) {//-----這里
num_locks++; // 鎖數(shù)加 1。
lock_order = num_locks; // 為此對象實(shí)例設(shè)置唯一的 lock_order。
}
}
public long lockOrder()
{
return lock_order;
}
public int[] array()
{
return arr;
}
}
class SomeClass implements Runnable
{
public int sumArrays(ArrayWithLockOrder a1,
ArrayWithLockOrder a2)
{
int value = 0;
ArrayWithLockOrder first = a1; // 保留數(shù)組引用的一個
ArrayWithLockOrder last = a2; // 本地副本。
int size = a1.array().length;
if (size == a2.array().length)
{
if (a1.lockOrder() > a2.lockOrder()) // 確定并設(shè)置對象的鎖定
{ // 順序。
first = a2;
last = a1;
}
synchronized(first) { // 按正確的順序鎖定對象。
synchronized(last) {
int[] arr1 = a1.array();
int[] arr2 = a2.array();
for (int i=0; i<size; i++)
value += arr1[i] + arr2[i];
}
}
}
return value;
}
public void run() {
//...
}
}
對于4,如果線程進(jìn)入,則線程在該類中所有操作不能進(jìn)行,包括靜態(tài)變量和靜態(tài)方法,實(shí)際上,對于含有靜態(tài)方法和靜態(tài)變量的代碼塊的同步,我們通常用4來加鎖.
-----------------------------
下面談一談一些常用的方法:
wait(),wait(long),notify(),notifyAll()等方法是當(dāng)前類的實(shí)例方法,
wait()是使持有對象鎖的線程釋放鎖;
wait(long)是使持有對象鎖的線程釋放鎖時間為long(毫秒)后,再次獲得鎖,wait()和wait(0)等價;
notify()是喚醒一個正在等待該對象鎖的線程,如果等待的線程不止一個,那么被喚醒的線程由jvm確定;
notifyAll是喚醒所有正在等待該對象鎖的線程.
在這里我也重申一下,我們應(yīng)該優(yōu)先使用notifyAll()方法,因?yàn)閱拘阉芯€程比喚醒一個線程更容易讓jvm找到最適合被喚醒的線程.
對于上述方法,只有在當(dāng)前線程中才能使用,否則報運(yùn)行時錯誤java.lang.IllegalMonitorStateException: current thread not owner.
--------------------------
下面,我談一下synchronized和wait()、notify()等的關(guān)系:
其實(shí)用生產(chǎn)者/消費(fèi)者這個例子最好說明他們之間的關(guān)系了:
public class test {
public static void main(String args[]) {
Semaphore s = new Semaphore(1);
Thread t1 = new Thread(s, "producer1");
Thread t2 = new Thread(s, "producer2");
Thread t3 = new Thread(s, "producer3");
Thread t4 = new Thread(s, "consumer1");
Thread t5 = new Thread(s, "consumer2");
Thread t6 = new Thread(s, "consumer3");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
}
}
class Semaphore
implements Runnable {
private int count;
public Semaphore(int n) {
this.count = n;
}
public synchronized void acquire() {
while (count == 0) {
try {
wait();
}
catch (InterruptedException e) {
//keep trying
}
}
count--;
}
public synchronized void release() {
while (count == 10) {
try {
wait();
}
catch (InterruptedException e) {
//keep trying
}
}
count++;
notifyAll(); //alert a thread that's blocking on this semaphore
}
public void run() {
while (true) {
if (Thread.currentThread().getName().substring(0,8).equalsIgnoreCase("consumer")) {
acquire();
}
else if (Thread.currentThread().getName().substring(0,8).equalsIgnoreCase("producer")) {
release();
}
System.out.println(Thread.currentThread().getName() + " " + count);
}
}
}
生產(chǎn)者生產(chǎn),消費(fèi)者消費(fèi),一般沒有沖突,但當(dāng)庫存為0時,消費(fèi)者要消費(fèi)是不行的,但當(dāng)庫存為上限(這里是10)時,生產(chǎn)者也不能生產(chǎn).請好好研讀上面的程序,你一定會比以前進(jìn)步很多.
上面的代碼說明了synchronized和wait,notify沒有絕對的關(guān)系,在synchronized聲明的方法、代碼塊中,你完全可以不用wait,notify等方法,但是,如果當(dāng)線程對某一資源存在某種爭用的情況下,你必須適時得將線程放入等待或者喚醒.
文章終于寫完了,基本上將我學(xué)習(xí)所得全部寫出來了,不過也留下些許遺憾,比如synchronized后是類時的深入的說明及討論.而且,文章由于自己能力有限,有些地方肯定會有錯誤,希望看過有何建議和批評,請發(fā)帖在下面,我會修正該文.謝謝!