1.何時使用多線程編程java
一個任務在正常狀況下是按順序執行的,可是若是當前任務裏有多個類似進程塊(例如for,while語句),咱們就能夠考慮把這些代碼塊抽出來並行運行,無需阻塞編程
2.實現多線程的幾種方式多線程
一種是繼承Thread類重寫run方法,另外一種是實現Runnable接口重寫run方法併發
啓動多線程不少狀況下是爲了處理併發進程,此時對於部分實時性要求不是那麼高的業務需求,咱們還能夠經過實現隊列的方式,異步實現。異步
3.舉例ide
繼承Thread測試
/** * * @ClassName: ThreadByEx * @Description: TODO * @author Mr.jqCheng * @date 2018年9月26日 * */ public class ThreadByEx extends Thread{ @Override public void run() { // TODO Auto-generated method stub System.out.println("我是繼承線程"); } }
實現Runnablethis
/** * * @ClassName: ThreadByRunnable * @Description: TODO * @author Mr.jqCheng * @date 2018年9月26日 * */ public class ThreadByRunnable implements Runnable{ /*public ThreadByRunnable() { this.run(); // TODO Auto-generated constructor stub }*/ public void run() { // TODO Auto-generated method stub System.out.println("我是實現進程"); } }
測試:spa
/** * * @ClassName: Test * @Description: TODO * @author Mr.jqCheng * @date 2018年9月26日 * */ public class Test { public static void main(String[] args) { // 繼承Thread啓動的方法 ThreadByEx t1 = new ThreadByEx(); t1.start();// 啓動線程 // 實現Runnable啓動線程的方法 ThreadByRunnable r = new ThreadByRunnable(); Thread t2 = new Thread(r); t2.start();// 啓動線程 //new ThreadByRunnable(); } }
運行結果:.net
我是繼承線程
我是實現進程
ok,簡單的多線程實現方式完成了,在調用start()的時候,該進程已經進入可執行狀態,等待系統執行。
線程處理的幾個經常使用方法:
package com.orange.util; /** * * @ClassName: Test * @Description: TODO * @author Mr.jqCheng * @date 2018年9月26日 * */ public class Test { public static void main(String[] args) { Thread deamon2 = new Thread(new DaemonRunner2(), "otherRunner"); deamon2.start();// 啓動線程 try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Thread deamon = new Thread(new DaemonRunner(), "DaemonRunner"); // 設置爲守護線程 deamon.setDaemon(true); deamon.start();// 啓動線程 } static class DaemonRunner implements Runnable { public void run() { // TODO Auto-generated method stub try { Thread.sleep(300); Thread t = Thread.currentThread(); System.out.println(t); } catch (Exception e) { e.printStackTrace(); } finally { System.out.println("進入守護線程,說明如今還有其餘線程在執行"); } } } static class DaemonRunner2 implements Runnable { public void run() { // TODO Auto-generated method stub try { Thread.sleep(1500); System.out.println("我是其餘線程"); } catch (Exception e) { e.printStackTrace(); } } } }
執行結果:
Thread[DaemonRunner,5,main]
進入守護線程,說明如今還有其餘線程在執行
我是其餘線程
首先,先啓動其餘線程,須要耗時1500ms,同時,主線程耗時1000ms後,開始進入守護線程,此時其它線程還在運行,到了守護線程,耗時300ms,其餘線程仍在執行,繼續往下,守護線程執行完畢
可是若是我把守護線程的300ms改爲500ms,會發生什麼事呢?
出現過兩種狀況,畢竟在臨界值
1.我是其餘線程
2.Thread[DaemonRunner,5,main]
進入守護線程,說明如今還有其餘線程在執行
我是其餘線程
本文來自 zejian_ 的CSDN 博客 ,全文地址請點擊:https://blog.csdn.net/javazejian/article/details/50878598?utm_source=copy