多線程

如何創建線程

Thread 類定義了多種方法可以被派生類重載,,必須重載run()方法
1.實現Runnable接口
   如果你不需要重載Tread的其它方法時,最好只實現Runnable接口
//  Create Thread method one is implements Runnable
class NewThread implements Runnable{
 Thread t;
 NewThread(){
  t = new Thread(this,"DemoThread");
  System.out.println("child thread : "+t);
  t.start();
 }
 public void run(){
  try{
   for (int n =5; n>0 ; n--){
    System.out.println("Child thread "+n);
    Thread.sleep(500);   // Child 500
   }   
  }catch(InterruptedException e){
   System.out.println("Child thread interrupted ");
  }
  System.out.println("Child thread exiting ");
 }
}

2 .可以繼承Thread類
    如果類僅在他們被加強或修改時應該被擴展
//  Create Thread the other method  is extends Thread
class NewThread2 extends Thread{
 
 NewThread2(){
  super("Demo Thread");
  System.out.println("child thread : "+this);
  start();
 }
 public void run(){
  try{
   for (int n =5; n>0 ; n--){
    System.out.println("Child thread "+n);
    Thread.sleep(500);   // Child 500
   }   
  }catch(InterruptedException e){
   System.out.println("Child thread interrupted ");
  }
  System.out.println("Child thread exiting ");
 }
}

同步
1.        當兩個或兩個線程需要共享資源,他們需要某種方法來確定資源在某一刻僅被一個線程佔用,叫同步(synchronization)
 2.        同步關鍵時管程(也叫信號量semaphone).管程是一個互斥佔鎖定的對象,或稱互斥體(mutex)====================================
1.創建線稱的兩個方法
2.t.join() 用於 控制主線程知道子線程何時結束 ,少用t.isAlive()
3.Priority
Level的值必須在MIN_PRIORITY到MAX_PRIORITY範圍內。通常,它們的值分別是1和10。要返回一個線程為默認的優先順序,指定NORM_PRIORITY,通常值為5。這些優先順序在Thread中都被定義為final型變數。(volatile的運用阻止了該優化)

4. synchronization
to method
class Callme {
    synchronized void call(String msg) {
    ...
}
調用第3方類時
ThirdClass tc = new ThirdClass()
synchronized(tc) {
   // statements to be synchronized
 }

5.wait( ),notify( )和notifyAll( )  這三個方法僅在synchronized方法中才能被調用
final void wait( ) throws InterruptedException
final void notify( )
final void notifyAll( )

6.死鎖

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章