java-多線程(上)

###24.01_多線程(多線程的引入)(瞭解)
* 1.什麼是線程
    * 線程是程序執行的一條路徑, 一個進程中能夠包含多條線程
    * 多線程併發執行能夠提升程序的效率, 能夠同時完成多項工做
* 2.多線程的應用場景
    * 紅蜘蛛同時共享屏幕給多個電腦
    * 迅雷開啓多條線程一塊兒下載
    * QQ同時和多我的一塊兒視頻
    * 服務器同時處理多個客戶端請求
    
###24.02_多線程(多線程並行和併發的區別)(瞭解)
* 並行就是兩個任務同時運行,就是甲任務進行的同時,乙任務也在進行。(須要多核CPU)
* 併發是指兩個任務都請求運行,而處理器只能按受一個任務,就把這兩個任務安排輪流進行,因爲時間間隔較短,令人感受兩個任務都在運行。
* 好比我跟兩個網友聊天,左手操做一個電腦跟甲聊,同時右手用另外一臺電腦跟乙聊天,這就叫並行。
* 若是用一臺電腦我先給甲發個消息,而後馬上再給乙發消息,而後再跟甲聊,再跟乙聊。這就叫併發。

###24.03_多線程(Java程序運行原理和JVM的啓動是多線程的嗎)(瞭解)
* A:Java程序運行原理
    * Java命令會啓動java虛擬機,啓動JVM,等於啓動了一個應用程序,也就是啓動了一個進程。該進程會自動啓動一個 「主線程」 ,而後主線程去調用某個類的 main 方法。
    
* B:JVM的啓動是多線程的嗎
    * JVM啓動至少啓動了垃圾回收線程和主線程,因此是多線程的。

###24.04_多線程(多線程程序實現的方式1)(掌握)
* 1.繼承Thread
    * 定義類繼承Thread
    * 重寫run方法
    * 把新線程要作的事寫在run方法中
    * 建立線程對象
    * 開啓新線程, 內部會自動執行run方法
    * 
        
            public class Demo2_Thread {
        
                /**
                 * @param args
                 */
                public static void main(String[] args) {
                    MyThread mt = new MyThread();                            //4,建立自定義類的對象
                    mt.start();                                                //5,開啓線程
                    
                    for(int i = 0; i < 3000; i++) {
                        System.out.println("bb");
                    }
                }
            
            }
            class MyThread extends Thread {                                    //1,定義類繼承Thread
                public void run() {                                            //2,重寫run方法
                    for(int i = 0; i < 3000; i++) {                            //3,將要執行的代碼,寫在run方法中
                        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaa");
                    }
                }
            }

###24.05_多線程(多線程程序實現的方式2)(掌握)
* 2.實現Runnable
    * 定義類實現Runnable接口
    * 實現run方法
    * 把新線程要作的事寫在run方法中
    * 建立自定義的Runnable的子類對象
    * 建立Thread對象, 傳入Runnable
    * 調用start()開啓新線程, 內部會自動調用Runnable的run()方法

            public class Demo3_Runnable {
                /**
                 * @param args
                 */
                public static void main(String[] args) {
                    MyRunnable mr = new MyRunnable();                        //4,建立自定義類對象
                    //Runnable target = new MyRunnable();
                    Thread t = new Thread(mr);                                //5,將其看成參數傳遞給Thread的構造函數
                    t.start();                                                //6,開啓線程
                    
                    for(int i = 0; i < 3000; i++) {
                        System.out.println("bb");
                    }
                }
            }
            
            class MyRunnable implements Runnable {                            //1,自定義類實現Runnable接口
                @Override
                public void run() {                                            //2,重寫run方法
                    for(int i = 0; i < 3000; i++) {                            //3,將要執行的代碼,寫在run方法中
                        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaa");
                    }
                }
                
            }

###24.06_多線程(實現Runnable的原理)(瞭解)
* 查看源碼
    * 1,看Thread類的構造函數,傳遞了Runnable接口的引用 
    * 2,經過init()方法找到傳遞的target給成員變量的target賦值
    * 3,查看run方法,發現run方法中有判斷,若是target不爲null就會調用Runnable接口子類對象的run方法

###24.07_多線程(兩種方式的區別)(掌握)
* 查看源碼的區別:
    * a.繼承Thread : 因爲子類重寫了Thread類的run(), 當調用start()時, 直接找子類的run()方法
    * b.實現Runnable : 構造函數中傳入了Runnable的引用, 成員變量記住了它, start()調用run()方法時內部判斷成員變量Runnable的引用是否爲空, 不爲空編譯時看的是Runnable的run(),運行時執行的是子類的run()方法
    
* 繼承Thread
    * 好處是:能夠直接使用Thread類中的方法,代碼簡單
    * 弊端是:若是已經有了父類,就不能用這種方法
* 實現Runnable接口
    * 好處是:即便本身定義的線程類有了父類也不要緊,由於有了父類也能夠實現接口,並且接口是能夠多實現的
    * 弊端是:不能直接使用Thread中的方法須要先獲取到線程對象後,才能獲得Thread的方法,代碼複雜
###24.08_多線程(匿名內部類實現線程的兩種方式)(掌握)
* 繼承Thread類
         
        new Thread() {                                                    //1,new 類(){}繼承這個類
            public void run() {                                            //2,重寫run方法
                for(int i = 0; i < 3000; i++) {                            //3,將要執行的代碼,寫在run方法中
                    System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaa");
                }
            }
        }.start();
* 實現Runnable接口
            
        new Thread(new Runnable(){                                        //1,new 接口(){}實現這個接口
            public void run() {                                            //2,重寫run方法
                for(int i = 0; i < 3000; i++) {                            //3,將要執行的代碼,寫在run方法中
                    System.out.println("bb");
                }
            }
        }).start(); 

###24.09_多線程(獲取名字和設置名字)(掌握)
* 1.獲取名字
    * 經過getName()方法獲取線程對象的名字
* 2.設置名字
    * 經過構造函數能夠傳入String類型的名字
    * 
            new Thread("xxx") {
                public void run() {
                    for(int i = 0; i < 1000; i++) {
                        System.out.println(this.getName() + "....aaaaaaaaaaaaaaaaaaaaaaa");
                    }
                }
            }.start();
            
            new Thread("yyy") {
                public void run() {
                    for(int i = 0; i < 1000; i++) {
                        System.out.println(this.getName() + "....bb");
                    }
                }
            }.start(); 
    * 經過setName(String)方法能夠設置線程對象的名字
    * 
            Thread t1 = new Thread() {
                public void run() {
                    for(int i = 0; i < 1000; i++) {
                        System.out.println(this.getName() + "....aaaaaaaaaaaaaaaaaaaaaaa");
                    }
                }
            };
            
            Thread t2 = new Thread() {
                public void run() {
                    for(int i = 0; i < 1000; i++) {
                        System.out.println(this.getName() + "....bb");
                    }
                }
            };
            t1.setName("芙蓉姐姐");
            t2.setName("鳳姐");
            
            t1.start();
            t2.start();

###24.10_多線程(獲取當前線程的對象)(掌握)
* Thread.currentThread(), 主線程也能夠獲取
    * 
            new Thread(new Runnable() {
                public void run() {
                    for(int i = 0; i < 1000; i++) {
                        System.out.println(Thread.currentThread().getName() + "...aaaaaaaaaaaaaaaaaaaaa");
                    }
                }
            }).start();
            
            new Thread(new Runnable() {
                public void run() {
                    for(int i = 0; i < 1000; i++) {
                        System.out.println(Thread.currentThread().getName() + "...bb");
                    }
                }
            }).start();
            Thread.currentThread().setName("我是主線程");                    //獲取主函數線程的引用,並更名字
            System.out.println(Thread.currentThread().getName());        //獲取主函數線程的引用,並獲取名字
###24.11_多線程(休眠線程)(掌握)
* Thread.sleep(毫秒,納秒), 控制當前線程休眠若干毫秒1秒= 1000毫秒 1秒 = 1000 * 1000 * 1000納秒 1000000000

            new Thread() {
                public void run() {
                    for(int i = 0; i < 10; i++) {
                        System.out.println(getName() + "...aaaaaaaaaaaaaaaaaaaaaa");
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
            
            new Thread() {
                public void run() {
                    for(int i = 0; i < 10; i++) {
                        System.out.println(getName() + "...bb");
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
###24.12_多線程(守護線程)(掌握)
* setDaemon(), 設置一個線程爲守護線程, 該線程不會單獨執行, 當其餘非守護線程都執行結束後, 自動退出
    * 
            Thread t1 = new Thread() {
                public void run() {
                    for(int i = 0; i < 50; i++) {
                        System.out.println(getName() + "...aaaaaaaaaaaaaaaaaaaaaa");
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            
            Thread t2 = new Thread() {
                public void run() {
                    for(int i = 0; i < 5; i++) {
                        System.out.println(getName() + "...bb");
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            
            t1.setDaemon(true);                        //將t1設置爲守護線程
            
            t1.start();
            t2.start();
###24.13_多線程(加入線程)(掌握)
* join(), 當前線程暫停, 等待指定的線程執行結束後, 當前線程再繼續
* join(int), 能夠等待指定的毫秒以後繼續
    * 
            final Thread t1 = new Thread() {
                public void run() {
                    for(int i = 0; i < 50; i++) {
                        System.out.println(getName() + "...aaaaaaaaaaaaaaaaaaaaaa");
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            
            Thread t2 = new Thread() {
                public void run() {
                    for(int i = 0; i < 50; i++) {
                        if(i == 2) {
                            try {
                                //t1.join();                        //插隊,加入
                                t1.join(30);                        //加入,有固定的時間,過了固定時間,繼續交替執行
                                Thread.sleep(10);
                            } catch (InterruptedException e) {
                                
                                e.printStackTrace();
                            }
                        }
                        System.out.println(getName() + "...bb");
                    
                    }
                }
            };
            
            t1.start();
            t2.start();
###24.14_多線程(禮讓線程)(瞭解)
* yield讓出cpu

###24.15_多線程(設置線程的優先級)(瞭解)
* setPriority()設置線程的優先級

###24.16_多線程(同步代碼塊)(掌握)
* 1.什麼狀況下須要同步
    * 當多線程併發, 有多段代碼同時執行時, 咱們但願某一段代碼執行的過程當中CPU不要切換到其餘線程工做. 這時就須要同步.
    * 若是兩段代碼是同步的, 那麼同一時間只能執行一段, 在一段代碼沒執行結束以前, 不會執行另一段代碼.
* 2.同步代碼塊
    * 使用synchronized關鍵字加上一個鎖對象來定義一段代碼, 這就叫同步代碼塊
    * 多個同步代碼塊若是使用相同的鎖對象, 那麼他們就是同步的

            class Printer {
                Demo d = new Demo();
                public static void print1() {
                    synchronized(d){                //鎖對象能夠是任意對象,可是被鎖的代碼須要保證是同一把鎖,不能用匿名對象
                        System.out.print("黑");
                        System.out.print("馬");
                        System.out.print("程");
                        System.out.print("序");
                        System.out.print("員");
                        System.out.print("\r\n");
                    }
                }
    
                public static void print2() {    
                    synchronized(d){    
                        System.out.print("傳");
                        System.out.print("智");
                        System.out.print("播");
                        System.out.print("客");
                        System.out.print("\r\n");
                    }
                }
            }
###24.17_多線程(同步方法)(掌握)
* 使用synchronized關鍵字修飾一個方法, 該方法中全部的代碼都是同步的

        class Printer {
            public static void print1() {
                synchronized(Printer.class){                //鎖對象能夠是任意對象,可是被鎖的代碼須要保證是同一把鎖,不能用匿名對象
                    System.out.print("黑");
                    System.out.print("馬");
                    System.out.print("程");
                    System.out.print("序");
                    System.out.print("員");
                    System.out.print("\r\n");
                }
            }
            /*
             * 非靜態同步函數的鎖是:this
             * 靜態的同步函數的鎖是:字節碼對象
             */
            public static synchronized void print2() {    
                System.out.print("傳");
                System.out.print("智");
                System.out.print("播");
                System.out.print("客");
                System.out.print("\r\n");
            }
        }

###24.18_多線程(線程安全問題)(掌握)
* 多線程併發操做同一數據時, 就有可能出現線程安全問題
* 使用同步技術能夠解決這種問題, 把操做數據的代碼進行同步, 不要多個線程一塊兒操做
            
            public class Demo2_Synchronized {

                /**
                 * @param args
                 * 需求:鐵路售票,一共100張,經過四個窗口賣完.
                 */
                public static void main(String[] args) {
                    TicketsSeller t1 = new TicketsSeller();
                    TicketsSeller t2 = new TicketsSeller();
                    TicketsSeller t3 = new TicketsSeller();
                    TicketsSeller t4 = new TicketsSeller();
                    
                    t1.setName("窗口1");
                    t2.setName("窗口2");
                    t3.setName("窗口3");
                    t4.setName("窗口4");
                    t1.start();
                    t2.start();
                    t3.start();
                    t4.start();
                }
            
            }
            
            class TicketsSeller extends Thread {
                private static int tickets = 100;
                static Object obj = new Object();
                public TicketsSeller() {
                    super();
                    
                }
                public TicketsSeller(String name) {
                    super(name);
                }
                public void run() {
                    while(true) {
                        synchronized(obj) {
                            if(tickets <= 0) 
                                break;
                            try {
                                Thread.sleep(10);//線程1睡,線程2睡,線程3睡,線程4睡
                            } catch (InterruptedException e) {
                                
                                e.printStackTrace();
                            }
                            System.out.println(getName() + "...這是第" + tickets-- + "號票");
                        }
                    }
                }
            }

###24.19_多線程(火車站賣票的例子用實現Runnable接口)(掌握)


###24.20_多線程(死鎖)(瞭解)
* 多線程同步的時候, 若是同步代碼嵌套, 使用相同鎖, 就有可能出現死鎖
    * 儘可能不要嵌套使用
        
            private static String s1 = "筷子左";
            private static String s2 = "筷子右";
            public static void main(String[] args) {
                new Thread() {
                    public void run() {
                        while(true) {
                            synchronized(s1) {
                                System.out.println(getName() + "...拿到" + s1 + "等待" + s2);
                                synchronized(s2) {
                                    System.out.println(getName() + "...拿到" + s2 + "開吃");
                                }
                            }
                        }
                    }
                }.start();
                
                new Thread() {
                    public void run() {
                        while(true) {
                            synchronized(s2) {
                                System.out.println(getName() + "...拿到" + s2 + "等待" + s1);
                                synchronized(s1) {
                                    System.out.println(getName() + "...拿到" + s1 + "開吃");
                                }
                            }
                        }
                    }
                }.start();
            }

###24.21_多線程(之前的線程安全的類回顧)(掌握)
* A:回顧之前說過的線程安全問題
    * 看源碼:Vector,StringBuffer,Hashtable,Collections.synchroinzed(xxx)
    * Vector是線程安全的,ArrayList是線程不安全的
    * StringBuffer是線程安全的,StringBuilder是線程不安全的
    * Hashtable是線程安全的,HashMap是線程不安全的

java

相關文章
相關標籤/搜索