Java Thread 詳解

java 多線程Thread 詳解
1:首先需要理解線程的幾種狀態
阻塞狀態(等待i/o等) — 就緒狀態(等待cpu 輪轉) —執行狀態
2:調用了sleep 方法相當於強制讓線程睡覺,暫時不參與cpu 調度,效果上相當於使線程處於阻塞狀態
sleep 方法不會釋放已經佔有的鎖資源

3:調用yield 方法相當於讓線程主動讓出cpu 輪轉,即處於就緒狀態

4:join 方法是讓主線程等待該線程的執行結束,調用該方法會釋放已經佔有的鎖資源

5:interrupt 可以讓處於阻塞狀態的線程中斷。可以讓其跑出異常

6:daemon 守護進程,守護進程依賴於創建他的進程,比如在main 中創建一個 daemon 進程,main結束了,該守護進程也就結束了,比如gc 程序,但是用戶進程則不一樣,main 線程需要等待用戶線程的結束。

測試代碼比較亂

package concurrent;
/*
* @author: wjf
* @version: 2016年3月27日 上午9:54:26
*/

public class TestThread {
    private int count=0;
    private Object obj=new Object();

    public static void main(String[] args) throws InterruptedException{
        System.out.println(Thread.currentThread().getName()+"begin to exec");
        /*
         * join 可以 讓主線程等該該線程執行完
         */
//      TestThread test=new TestThread();
////        MyThread thread1=test.new MyThread();
////        MyThread thread2=test.new MyThread();
//      MyThread[] tt=new MyThread[10];
//      for(int i=0;i<10;i++){
//          tt[i]=test.new MyThread();
//          tt[i].start();
//          tt[i].interrupt();
//          tt[i].join();
//      }
//      
        //System.out.println(Thread.currentThread().getName()+"begin to wait");
        //thread1.join();
        //thread2.join();

        InterruptedThread it=new InterruptedThread();
        it.start();
//      it.interrupt();

        System.out.println(Thread.currentThread().getName()+"continue to exec");

//      while(Thread.activeCount()>1){
//          Thread.yield();
//      }

    }
    class MyThread extends Thread{
        public void run(){
            synchronized(obj){
//              System.out.println("count="+count);
                System.out.println(Thread.currentThread().getName()+"is running");
                for(int i=0;i<100000;i++){
                    count++;
                }
                /*
 * sleep 方法只是讓線程 睡眠,只是讓出了cpu 時間,並不會釋放 鎖,只是處於了就緒狀態 ,沒有處於阻塞狀態
 */
                //Thread.sleep(2000);
                // test yield
//              try {
//                  Thread.sleep(100);
//              } catch (InterruptedException e) {
//                  // TODO Auto-generated catch block
//                  e.printStackTrace();
//              }


                System.out.println(Thread.currentThread().getName()+"is done");
//              System.out.println("count="+count);
            }
        }
    }
}
class InterruptedThread extends Thread{
    public void run(){
        try{
            System.out.println(Thread.currentThread().getName()+"begin to sleep");
            Thread.sleep(1000);
        }catch (InterruptedException e){
            System.out.println(Thread.currentThread().getName()+"is interrupted");
        }finally{
            System.out.println(Thread.currentThread().getName()+"exec is done");
        }
    }
}
發佈了40 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章