JAVA多線程的總結

來源:互聯網
上載者:User

標籤:安全執行緒   安全   idt   void   image   應用   反射   tor   搶佔式   

1-----------------------------------基本概念-------------------------------------------------

(1)多線程:一個應用程式有多條執行路徑
        進程:正在執行的應用程式
        線程:進程的執行單元,執行路徑
        單線程:一個應用程式只有一條執行路徑
        多線程:一個應用程式有多條執行路徑
        多進程的意義?
            提高CPU的使用率
        多線程的意義?
            提高應用程式的使用率

(2)多線程的實現方案
        A:繼承Thread類
        B:實現Runnable介面

(3)線程的調度
        A:線程的調度
            a:分時調度
            b:搶佔式調度 (Java採用的是該調度方式)

(4)同步解決安全執行緒問題
        A:同步代碼塊
            synchronized(對象) {
                需要被同步的代碼;
            }
            
            這裡的鎖對象可以是任意對象。
            
        B:同步方法
            把同步加在方法上。
            
            這裡的鎖對象是this
            
        C:靜態同步方法
            把同步加在方法上。
            
            這裡的鎖對象是當前類的位元組碼檔案對象(反射再講位元組碼檔案對象)

(5)線程的生命週期

     

2-----------------------------------基礎代碼-------------------------------------------------

(1)繼承Thread

/**
 * 繼承Thread
 * @author Administrator
 *
 */
   public class XC1 extends Thread {

           String bb =null ;
    
           public XC1(){}
    
           public XC1(String aa){
                 super();
                 bb=aa;
    }
    
    @Override
    public void run() {
           for (int i = 0; i < 1000; i++) {
                   System.out.println("線程1:"+1111+bb);
        }
    }
}
(2)實現Runnable介面


public class XC2 implements Runnable {

    
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("線程2:"+2222);
        }
    }

}
(3)調用


public class Demo1 {

    public static void main(String[] args) {

        XC1 xc1 = new XC1();
        Thread th1 = new Thread(xc1);
        th1.start();
        XC2 xc2 = new XC2();
        Thread th2 = new Thread(xc2);
        th2.start();

 

    }

}

 

JAVA多線程的總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.