進程:啓動一個應用程序,就會開啓一個進程(微信,QQ,瀏覽器等等)瀏覽器
線程:程序的執行路徑微信
進程和線程的區別:進程是在操做系統下的併發,線程是在應用程序下的併發多線程
多線程:在同一進程中開啓了多個不一樣的執行路徑,多個路徑同時執行併發
多線程好處:提升程序總體運行速度,快速響應異步
多線程的應用場景:ide
CPU切換:this
單核CPU:同一時刻只有一個線程能夠工做,線程上下文切換耗費資源操作系統
多核CPU:同一時刻多個線程同時工做,上下文切換較少線程
多線程越多越好?日誌
小型項目:使用多線程異步
大型項目:使用MQ代替多線程
用戶線程和守護線程的區別:
用戶線程當主線程中止後,用戶線程也會一直運行。thread.setDaemon(false);
而守護線程當咱們主線程中止後,守護線程也會中止。thread.setDaemon(true);
建議採用變量的方式中止線程
public class Thread005 extends Thread { private volatile boolean flag = true; @Override public void run() { System.out.println(Thread.currentThread().getName()); while (flag) { } } public void stopThread() { this.flag = false; } public static void main(String[] args) { Thread005 thread005 = new Thread005(); thread005.start(); try { Thread.sleep(3000); thread005.stopThread(); } catch (Exception e) { } } }
當在主線程當中執行到t1.join()方法時,就認爲主線程應該把執行權讓給t1
class Main { public static void main(String[] args) { Thread thread = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i <10 ; i++) { System.out.println("子線程..."); } } }); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } for (int i = 0; i <10 ; i++) { System.out.println("main線程....."); } System.out.println("主線程銷燬...."); } }