在前面一篇介紹了線程的生命週期【併發編程之多線程概念 】,在本篇將正式介紹如何建立、中斷線程,以及線程是如何銷燬的。最後,咱們會講解一些常見的線程API。html
線程建立java
Java 5 之前,實現線程有兩種方式:擴展java.lang.Thread類,實現java.lang.Runnable接口。這兩種方式都是都是直接建立線程,而每次new Thread都會消耗比較大的資源,致使每次新建對象時性能差;並且線程缺少統一管理,可能無限制新建線程,相互之間競爭,極可能佔用過多系統資源致使死機或OOM。同時,new Thread的線程缺少更多功能,如定時執行、按期執行、線程中斷。編程
Java 5開始,JDK提供了4中線程池(newFixedThreadPool、newCachedThreadPool、newScheduledThreadPool、newSingleThreadExecutor)來獲取線程。這樣作的好處是:能夠重用已經存在的線程,減小對象建立、消亡的開銷,性能佳;並且線程池可有效控制最大併發線程數,提升系統資源的使用率,同時避免過多資源競爭,避免堵塞。經過特定的線程池也能夠實現定時執行、按期執行、單線程、併發數控制等功能。緩存
建立線程的代碼實現安全
//1.自定義一個類繼承Thread類 public class ExThread extends Thread { //2.重寫run() @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName()+」:」+i); } } public static void main(String[] args) { //3.建立Thread子類對象 ExThread exThread = new ExThread(); //4.調用start方法啓動自定義線程 exThread.start(); } }
//1.自定義一個類實現Runnable接口 public class ImThread implements Runnable{ //2.實現run() @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName()+」:」+i); } } public static void main(String[] args) { //3.建立Runnable實現類對象 ImThread imThread = new ImThread(); //4.建立Thread對象 Thread thread = new Thread(imThread); //5.調用start()開啓線程 thread.start(); } }
建立一個固定線程數的線程池,可控制線程最大併發數,超出的線程會在隊列中等待多線程
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CreateThreadByFixedPool { /** * Cover Runnable.run() */ private static void run(){ System.out.println(Thread.currentThread().getName()+" is running..."); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { ExecutorService pool = Executors.newFixedThreadPool(3); for (int i = 0; i < 10; i++) { pool.execute(CreateThreadByFixedPool::run); } } }
建立一個可緩存線程池,若是線程池長度超過處理須要,可靈活回收空閒線程,若無可回收,則新建線程.併發
線程池的容量爲無限大,當執行第二個任務時第一個任務已經完成,會複用執行第一個任務的線程,而不用每次新建線程。ide
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CreateThreadByCachedPool { public static void main(String[] args) { ExecutorService pool = Executors.newCachedThreadPool(); for (int i = 0; i < 10; i++) { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } pool.execute(() -> System.out.println(Thread.currentThread().getName()+" is running...")); } } }
建立一個固定線程數的線程池,支持定時及週期性任務執行。工具
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class CreateThreadByScheduledPool { public static void main(String[] args) { ScheduledExecutorService pool = Executors.newScheduledThreadPool(3);
//delay 2s excute. pool.schedule(() -> System.out.println(Thread.currentThread().getName()+" delays 2s "), 2, TimeUnit.SECONDS);
//delay 2s and every 3s excute. pool.scheduleAtFixedRate(() -> System.out.println(Thread.currentThread().getName()+" delays 2s every 3s execte"), 2, 3, TimeUnit.SECONDS); } }
建立一個單線程化的線程池,它只會用惟一的工做線程來執行任務,保證全部任務按照指定順序(FIFO, LIFO, 優先級)執行。post
public class CreateThreadBySingleThreadPool { public static void main(String[] args) { ExecutorService pool = Executors.newSingleThreadExecutor(); for (int i = 0; i < 10; i++) { final int index = i; pool.execute(() ->{ System.out.println(String.format("The thread %d (%s) is running...", index,Thread.currentThread().getName())); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } }); } } }
Thread負責線程自己相關的職責和控制,Runnable負責邏輯業務。
線程中斷
線程銷燬
public static void main(String[] args) throws InterruptedException { Thread t = new Thread(){ @Override public void run() { System.out.println("I will start work."); while(!isInterrupted()){ System.out.println("working...."); } System.out.println("I will exit."); } }; t.start(); TimeUnit.MICROSECONDS.sleep(100); System.out.println("System will exit."); t.interrupt(); }
public class FlagThreadExit { static class MyTask extends Thread{ private volatile boolean closed = false; @Override public void run() { System.out.println("I will start work."); while(!closed && !isInterrupted()){ System.out.println("working...."); } System.out.println("I will exit."); } public void closed(){ this.closed = true; this.interrupt(); } } public static void main(String[] args) throws InterruptedException { MyTask task = new MyTask(); task.start(); TimeUnit.MICROSECONDS.sleep(100); System.out.println("System will exit."); task.closed(); } }
多線程API
方法
|
返回值
|
做用
|
|
yield()
|
static void
|
暫停當前正在執行的線程對象,並執行其餘線程。
|
只有優先級大於等於該線程優先級的線程(包括該線程)纔有機會被執行
釋放CPU資源,不會放棄monitor鎖
|
sleep()
|
static void
|
使當前線程休眠,其它任意線程都有執行的機會
|
釋放CPU資源,不會放棄monitor鎖
|
wait()
|
void
|
使當前線程等待
|
Object的方法
|
interrupt()
|
void
|
中斷線程
|
可中斷方法
|
interrupted()
|
static boolean
|
判斷當前線程是否中斷
|
|
isInterrupted()
|
boolean
|
測試線程是否已經中斷
|
|
join()
|
void
|
在線程A內,join線程B,線程A會進入BLOCKED狀態,直到線程B結束生命週期或者線程A的BLOCKED狀態被另外的線程中斷
|
可中斷方法
|
wait使用
public class WaitDemo { public static void main(String[] args) { ExecutorService pool = Executors.newFixedThreadPool(2); pool.execute(() -> { synchronized (WaitDemo.class){ System.out.println("Enter Thread1..."); System.out.println(Thread.currentThread().getName()+" is waiting..."); try { WaitDemo.class.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread1 is going..."); System.out.println("Shut down Thread1."); } }); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } pool.execute(() ->{ synchronized (WaitDemo.class) { System.out.println("Enter Thread2..."); System.out.println(Thread.currentThread().getName()+" is notifying other thread..."); WaitDemo.class.notify(); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread2 is going..."); System.out.println("Shut down Thread2."); } }); } }
補充