顯示具有 執行緒 標籤的文章。 顯示所有文章
顯示具有 執行緒 標籤的文章。 顯示所有文章

2011年4月11日 星期一

JAVA筆記-wait()、notify()、notifyAll() 執行緒間的等待與喚醒機制的互動

必須撰寫在synchronized的區塊內,
當wait()被呼叫時,則會釋放所有的鎖,
並寫在try-catch(InterruptedException e)內,

1. void wait()
讓執行緒進入等待狀態
2. void notify()
喚醒一個等待中的執行緒,若有多個執行緒,則由JVM決定
3. void notifyAll()
喚醒所有等待中的執行緒

注意:考慮在複雜程式上的邏輯正確,在執行緒交互呼叫wait()和notify()時,可能先配合滿足的條件再呼叫函式,例如設計前置布林值或計數器來作為呼叫的條件
##ReadMore##
import static java.lang.System.out;
public class Ex_WaitNotify {
  public static void main(String[] args) {
    One one = new One();
    one.start();
    synchronized(one) { // 主執行緒取得one的鎖
      String tName = Thread.currentThread().getName();
      out.print("one 進入 wait pool ");
      out.println("(" + tName + ")");
      try {
        one.wait();
      } catch (InterruptedException e) {}
      out.print("one 離開 wait pool ");
      out.println("(" + tName + ")");
    }
  }
}

class One extends Thread {
  public void run() {
    synchronized (this) {
      String tName = Thread.currentThread().getName();
      out.print("呼叫 notify() ");
      out.println("(" + tName + ")");
      notify();
      out.print("notify() 呼叫完畢! ");
      out.println("(" + tName + ")");
    }
  }
}

JAVA筆記-synchronized 同步物件資料,避免Race Condition

當多執行緒存取一共享變數時,會有race condition問題,
亦即變數產生不一致性的同步問題,
JAVA提供synchronized的方法,利用lock來鎖定物件,
使得在同一時間內最多只能予許一個執行緒存取共享變數

synchronized有兩種撰寫方法:
1. synchronized method
當同時有多個執行緒存取方法時,先到者優先使用,
後到者必須持續等待前一個執行緒執行完離開方法後,
釋放其lock才可進入使用
synchronized method其lock是該類別的lock,
因此如果這個類別擁有兩個以上的同步化方法,
而又有多個執行緒存取該類別不同個的同步化方法,
也是只會只有一個執行緒可以正常進入執行,
其他執行緒仍然必須等待,因為lock是class lock,
鎖住的是一整個類別
public class Sync {
  public synchronized void one(...){...}
  public synchronized void two(...){...}
}

2. synchronizated block
為了減少synchronized過於影響執行效率,所以期望把受影響的範圍縮小,
因此使用其他物件來當lock,但仍然可用class lock,將lock指定為this即可
public void three{
  synchronized (lock) {...}
}


關於static method synchronized,
我的觀念不夠成熟,可能不夠充足與正確,
所以不多闡述,可參考[Java] Synchronized 心得

在所有類別上,同時只有一個執行緒可以執行在synchronized static method;
而對於同一個類別所new出來的instance,
同時只有一個執行緒可以執行它自己的synchronized method(non-static),
因為每一個instance是鎖自己的lock

2011年4月9日 星期六

JAVA筆記-Thread 多執行緒基本撰寫範例與常用函式

public class Thread extends Object implements Runnable
Thread繼承了Object類別,並由於是因為需實作Runnable介面,
所以要撰寫run()來運行想要的程序,Thread程式撰寫方法有兩種:

1. 繼承Thread類別(撰寫較為容易,本身已繼承類別之類別,將無法再繼承Thread類別)
public class Test
  public static void main(String[] args){
    HelloThread t1 = new HelloThread();
    HelloThread t2 = new HelloThread();
    t1.setName("T1");
    t1.setName("T2");
    t1.start();
    t2.start();
    // 取得目前執行緒數量
    System.out.println(Thread.activeCount());
  }
}
class HelloThread extends Thread{
  public void run(){
    for(int i=1; i<100; i++){
      // 取得目前執行緒名稱
      String tName = Thread.currentThread().getName();     System.out.println(tName + ":" + i);
    }
  }
}

2. 實作Runnable介面(程式有共同介面標準,可避免單一繼承問題)
public class Test
  public static void main(String[] args){
    HellowThread t1 = new HelloThread();
    HellowThread t2 = new HelloThread();
    Thread t1 = new Thread(t1, "T1");
    Thread t2 = new Thread(t2, "T2");
    t1.start();
    t2.start();
    // 取得目前執行緒數量
    System.out.println(Thread.activeCount());
  }
}
class HelloThread implements Runnable{
  public void run(){
    for(int i=1; i<100; i++){
      // 取得目前執行緒名稱
      String tName = Thread.currentThread().getName();       System.out.println(tName + ":" + i);
    }
  }
}

##ReadMore##
建構子方法:
1. Thread() 分派新的執行緒
2. Thread(String name)
3. Thread(Runnable target) 傳入一個Runnable物件,並分派新的執行緒
4. Thread(Runnable target, String name)

常用方法:
1. String getName() 取得名稱
2. int getPriority() 取得優先權
3. void setPriority() 可設參數1~10或MIN_PRIORITY=1、NORM_PRIORITY=5、MAX_PRIORITY=10
4. void start 將執行丟入Runnable pool中,等待系統run()呼叫
5. void run() 開始執行工作(由系統自動呼叫,非程式設計師撰寫)
6. static void yield() 將目前執行緒先行暫停,重新排程,讓與其他執行緒執行
7. static void sleep(long millis) 暫停目前執行緒,需在try-catch中呼叫,會丟出throws InterruptedException
8. void join() / void join(long millis) 用於調整執行緒執行順序,先暫停目前執行緒,而指定其他執行緒加入執行工作,執行完畢後才回復,或可設定執行時間,需在try-catch中呼叫,會丟出throws InterruptedException
9. void stop() 停止正在執行的執行緒 (不建議使用,易造成死結)
10. void suspend() 停止正在執行的執行緒 (不建議使用,易造成死結)
11. void destroy() 毀掉執行緒
12. boolean isAlive() 取得目前執行緒狀態
13. void wait() 讓執行緒進入等待狀態
14. void notify() 喚醒一個等待中的執行緒,若有多個執行緒,則由JVM決定
15. void notifyAll() 喚醒所有等待中的執行緒

2010年9月15日 星期三

Java筆記-Deadlock 死結

不當使用synchronized,造成執行緒資源互鎖,程式無法結束 ##ReadMore## public class Deadlock {
  public static main(String[] args) {
    final Object r1 = "r1";
    final Object r2 = "r2";
    Thread t1 = new Thread() {
      public void run() {
        synchronized(r1) {
          System.out.println("T1 : locked r1");
          try {Thread.sleep(150);}
          catch(InterruptedException e) {}
          synchronized(r2) {
            System.out.println("T1 : locked r2");
          }
        }
      }
    };
    Thread t2 = new Thread() {
      public void run() {
        synchronized(r2) {
          System.out.println("T2 : locked r2");
          try {Thread.sleep(50);}
          catch(InterruptedException e) {}
          synchronized(r1) {
            System.out.println("T2 : locked r1");
          }
        }
      }
    };
    t1.start();
    t2.start();
  }
}

結果輸出:(程式無法停止執行)
T1 : locked r1
T2 : locked r2
/