1.什么時候使用多線程編程
一個任務在正常情況下是按順序執行的,但是如果當前任務里有多個相似進程塊(例如for,while語句),我們就可以考慮把這些代碼塊抽出來并行運行,無需阻塞
2.實現多線程的幾種方式
一種是繼承Thread類重寫run方法,另一種是實現Runnable接口重寫run方法
啟動多線程很多情況下是為了處理并發進程,此時對于部分實時性要求不是那么高的業務需求,我們還可以通過實現隊列的方式,異步實現。
3.舉例
繼承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("我是繼承線程"); } }
實現Runnable
/** * * @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("我是實現進程"); } }
測試:
/** * * @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(); } }
運行結果:
我是繼承線程
我是實現進程
ok,簡單的多線程實現方式完成了,在調用start()的時候,該進程已經進入可執行狀態,等待系統執行。
線程處理的幾個常用方法:
void interrupt():向線程發送中斷請求,線程的中斷狀態將會被設置為true,如果當前線程被一個sleep調用阻塞,那么將會拋出interrupedException異常。
static boolean interrupted():測試當前線程(當前正在執行命令的這個線程)是否被中斷。注意這是個靜態方法,調用這個方法會產生一個副作用那就是它會將當前線程的中斷狀態重置為false。
boolean isInterrupted():判斷線程是否被中斷,這個方法的調用不會產生副作用即不改變線程的當前中斷狀態。
static Thread currentThread() : 返回代表當前執行線程的Thread對象。
守護進程
用來服務于不是服務進程的其他所有當前進程下的所有線程
實現deamon.setDaemon(true)就行,要在線程開啟之前啟用
舉例
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]
進入守護線程,說明現在還有其他線程在執行
我是其他線程
新聞熱點
疑難解答
圖片精選