目錄
    多線程  一、線程概述  1. 進程   正在執行的應用程序(java.exe),一個可執行的程序一次運行的過程
  獨立性:不同進程之間相互獨立 動態性:是一直活動的 并發性:多個進程可以在單個處理器上同時運行
 2. 線程   線程是程序中的一個執行流,每個線程都有自己的專有寄存器,但代碼區是共享的,即不同的線程可以執行同樣的函數
 各線程在運行過程中可能會出現資源競爭 CPU在不同的線程之間切換 每個線程的執行機會相對隨機
 3. 進程與線程 一個線程只能屬于一個進程 一個進程可以有多個線程,至少有一個主線程 同一進程的所有線程共享系統分配給該進程的資源 線程是指進程內的一個執行單元,也是進程內的可調度實體 系統創建進程時需要重新分配資源,而創建線程相對容易,因此效率更高
 4. 多線程   多線程是指程序中包含多個執行流,也就是說允許單個程序創建多個并行執行的線程來完成各自的任務
 5. 主線程   任何一個Java程序啟動時,一個線程立刻運行,執行main方法(程序的入口),這個線程稱為程序的主線程
  1. 繼承Thread類   Thread類中的run方法本身并不執行任何操作,需要繼承Thread類后重寫該方法
  // TODO 線程實現實現方式:繼承Thread類System.out.println(111);// 1.聲明一個定義的線程對象 - 父類引用指向子類對象Thread thread1 = new MyThread();thread1.setName("子線程1");// 2.使一個線程進入到就緒狀態:start()方法// 線程啟動后會調用相應的run方法thread1.start();// 直接調用run方法相當于執行一個普通類下的普通方法// 此時程序會等待方法調用完成后按順序執行thread1.run();System.out.println(222);// 多個子線程在執行時,執行的機會相對隨機Thread thread2 = new MyThread("子線程2");thread2.start();thread2.run();System.out.println(333); 
// 實現線程的方式 - 繼承Thread類
public class MyThread extends Thread {// 顯示聲明空的構造方法public MyThread() {}// 子類中調用父類的構造方法public MyThread(String name) {// 在線程實例化時指定線程名稱super(name);}// 重寫run方法public void run() {for (int i = 0; i < 10; i++) {// Thread.currentThread()獲得當前所在線程的對象if (i == 5) {if (Thread.currentThread().getName().equals("子線程1")) {// 當某一個線程中出現異常時,不會影響另外一個線程System.out.println(1/0);}}System.out.println(Thread.currentThread() + ":" + i);}}} 
// TODO 多線程練習:相對獨立的線程 - 繼承Thread// 某個商城進行促銷活動,商城內存在多個商家// -》類比思想:商場開門 - 主線程啟動System.out.println("商場開門");// 每個商家售賣不同的商品,并有不同的庫存Thread thread1 = new ShopThread("夏季T恤", 35, "李寧品牌服裝店");Thread thread2 = new ShopThread("潔面神器", 50, "韓國護膚品牌店");Thread thread3 = new ShopThread("kindle", 30, "亞馬遜直銷店");// -》封裝實體:能夠刻畫商家售賣商品以及表示庫存// 描述該商城當天開門直到所有商家商品售空的過程thread1.start();thread2.start();thread3.start();thread1.join();thread2.join();thread3.join();// -》類比思想:商品售空,庫存為0時線程正常停止// 使用兩種方式實現System.out.println("商場關門"); // 多家店鋪同時售賣商品
public class ShopThread extends Thread {public ShopThread() {}public ShopThread(String productName, Integer count, String name) {super(name);this.count = count;this.productName = productName;}// 售賣的商品private String productName;// 商品的庫存private Integer count;public String getProductName() {return productName;}public void setProductName(String productName) {this.productName = productName;}public Integer getCount() {return count;}public void setCount(Integer count) {this.count = count;}// 使用相對隨機的方式減少商品的庫存public void run() {for (int i = count; i > 0;) {if ((--i) != 0) {// 通過線程的name屬性刻畫商家的名稱System.out.println(Thread.currentThread().getName() + "賣出一件" + this.productName + ",僅剩" + i + "件");} else {System.out.println(Thread.currentThread().getName() + "商品已售完,關店");}}}} 
2. 實現Runnable接口  // 自定義類實現Runnable接口
public class MyRunnable implements Runnable {// 重寫run方法@Overridepublic void run() {for (int i = 0; i < 10; i++) {// 獲得當前線程的名稱System.out.println(Thread.currentThread().getName() + ":" + i);}}
} 
public class RunnableTest {public static void main(String[] args) {// 將一個實現了Runnalbe接口的實現類的實例傳入MyRunnable myRunnable1 = new MyRunnable();MyRunnable myRunnable2 = new MyRunnable();// 調用相應的構造方法,指定線程名Thread thread1 = new Thread(myRunnable1, "線程1");// 啟動線程thread1.start();// 調用相應的構造方法,指定線程名      Thread thread2 = new Thread(myRunnable2, "線程2");// 啟動線程thread2.start();}
} 
// TODO 多線程練習:相對獨立的線程 - 實現RunnableSystem.out.println("商場開門");// 實例化Runnable接口的對象Runnable runnable1 = new ShopRunnable("夏季T恤", 350);Runnable runnable2 = new ShopRunnable("潔面神器", 500);Runnable runnable3 = new ShopRunnable("kindle", 300);// 通過線程控制目標對象Thread thread1 = new Thread(runnable1, "李寧品牌服裝店");Thread thread2 = new Thread(runnable2, "韓國護膚品牌店");Thread thread3 = new Thread(runnable3, "亞馬遜直銷店");// 線程啟動thread1.start();thread2.start();thread3.start();// 可以設置最長等待時長// 超過等待時長,繼續運行當先線程內容// 不指定時長時,等待線程完全執行完畢再執行當前線程thread1.join(10);thread2.join(10);thread3.join(10);System.out.println("商場關門"); // 多家店鋪同時售賣商品
public class ShopRunnable implements Runnable {public ShopRunnable() {}public ShopRunnable(String productName, Integer count) {this.count = count;this.productName = productName;}// 售賣的商品private String productName;// 商品的庫存private Integer count;public String getProductName() {return productName;}public void setProductName(String productName) {this.productName = productName;}public Integer getCount() {return count;}public void setCount(Integer count) {this.count = count;}// 使用相對隨機的方式減少商品的庫存public void run() {for (int i = count; i > 0;) {if ((--i) != 0) {// 通過線程的name屬性刻畫商家的名稱System.out.println(Thread.currentThread().getName() + "賣出一件" + this.productName + ",僅剩" + i + "件");}else {System.out.println(Thread.currentThread().getName() + "商品已售完,關店");}}}} 
3. 內部類方式創建  public class ThreadInner {public static void main(String[] args) {// 使用匿名內部類實現線程執行具體內容new Thread("新線程") {@Overridepublic void run() {for (int i = 0; i < 10; i++) {System.out.println(this.getName() + ":" + i);}}// 啟動線程}.start();}
} 
public class RunnableInner {public static void main(String[] args) {// 實例化線程new Thread(new Runnable() {@Overridepublic void run() {for (int i = 0; i < 10; i++) {System.out.println(Thread.currentThread().getName() + ":" + i);}}// 啟動線程}, "新線程").start();}
} 
四、線程常用方法  1. 設置線程名稱   默認情況下線程的優先級與創建它的父線程具有相同的優先級,提升搶到時間片的概率,從而獲得更多的執行機會
  setPriority(int newPriority):參數范圍為1-10,需要在執行start()方法前設置
 4. 等待某一線程終止 join():先執行start()方法,再執行join方法,當前線程執行完畢后,會繼續執行其它線程
 5. 后臺線程   也稱為守護線程或用戶線程,如JVM的垃圾回收線程,必須在start()前執行,如果所有的前臺線程都死亡,則會自動死亡
 setDaemon(boolean on)
 五、生命周期   線程啟動后進入到就緒狀態,多個線程在同時運行時,不斷的在爭搶CPU的時間片
 
 public class Ticket implements Runnable {// 使用private定義競爭資源private int ticket = 100;@Overridepublic void run() {while (true) {// 對當前線程進行同步加鎖synchronized (this) {ticket--;// 當車票售空時跳出循環if (ticket < 0) {break;}System.out.println(Thread.currentThread().getName() + "購買,當前剩余票數:" + ticket);}}}
} 
public class TicketTest {// 模擬兩名旅客的搶票public static void main(String[] args) {Ticket ticket = new Ticket();Thread thread1 = new Thread(ticket,"旅客1");Thread thread2 = new Thread(ticket,"旅客2");thread1.start();thread2.start();}
}
 
轉載于:https://www.cnblogs.com/yokii/p/9445151.html
                            總結 
                            
                                以上是生活随笔 為你收集整理的020.day20 线程概述 多线程优缺点 线程的创建 线程常用方法 生命周期 多线程同步... 的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                            
                                如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。