這篇文章主要講解了“線程、多線程和線程池的區(qū)別有哪些”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“線程、多線程和線程池的區(qū)別有哪些”吧!
創(chuàng)新互聯(lián)建站是專業(yè)的潁州網(wǎng)站建設(shè)公司,潁州接單;提供做網(wǎng)站、成都網(wǎng)站設(shè)計,網(wǎng)頁設(shè)計,網(wǎng)站設(shè)計,建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進行潁州網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團隊,希望更多企業(yè)前來合作!
在操作系統(tǒng)中,線程是比進程更小的能夠獨立運行的基本單位。同時,它也是CPU調(diào)度的基本單位。線程本身基本上不擁有系統(tǒng)資源,只是擁有一些在運行時需要用到的系統(tǒng)資源,例如程序計數(shù)器,寄存器和棧等。一個進程中的所有線程可以共享進程中的所有資源。
多線程可以理解為在同一個程序中能夠同時運行多個不同的線程來執(zhí)行不同的任務(wù),這些線程可以同時利用CPU的多個核心運行。多線程編程能夠最大限度的利用CPU的資源。如果某一個線程的處理不需要占用CPU資源時(例如IO線程),可以使當(dāng)前線程讓出CPU資源來讓其他線程能夠獲取到CPU資源,進而能夠執(zhí)行其他線程對應(yīng)的任務(wù),達到最大化利用CPU資源的目的。
在Java中,實現(xiàn)線程的方式大體上分為三種,通過繼承Thread類、實現(xiàn)Runnable接口,實現(xiàn)Callable接口。簡單的示例代碼分別如下所示。
package io.binghe.concurrent.executor.test; /** * @author binghe * @version 1.0.0 * @description 繼承Thread實現(xiàn)線程 */ public class ThreadTest extends Thread { @Override public void run() { //TODO 在此寫在線程中執(zhí)行的業(yè)務(wù)邏輯 } }
package io.binghe.concurrent.executor.test; /** * @author binghe * @version 1.0.0 * @description 實現(xiàn)Runnable實現(xiàn)線程 */ public class RunnableTest implements Runnable { @Override public void run() { //TODO 在此寫在線程中執(zhí)行的業(yè)務(wù)邏輯 } }
package io.binghe.concurrent.executor.test; import java.util.concurrent.Callable; /** * @author binghe * @version 1.0.0 * @description 實現(xiàn)Callable實現(xiàn)線程 */ public class CallableTest implements Callable<String> { @Override public String call() throws Exception { //TODO 在此寫在線程中執(zhí)行的業(yè)務(wù)邏輯 return null; } }
一個線程從創(chuàng)建,到最終的消亡,需要經(jīng)歷多種不同的狀態(tài),而這些不同的線程狀態(tài),由始至終也構(gòu)成了線程生命周期的不同階段。線程的生命周期可以總結(jié)為下圖。
其中,幾個重要的狀態(tài)如下所示。
NEW:初始狀態(tài),線程被構(gòu)建,但是還沒有調(diào)用start()方法。
RUNNABLE:可運行狀態(tài),可運行狀態(tài)可以包括:運行中狀態(tài)和就緒狀態(tài)。
BLOCKED:阻塞狀態(tài),處于這個狀態(tài)的線程需要等待其他線程釋放鎖或者等待進入synchronized。
WAITING:表示等待狀態(tài),處于該狀態(tài)的線程需要等待其他線程對其進行通知或中斷等操作,進而進入下一個狀態(tài)。
TIME_WAITING:超時等待狀態(tài)。可以在一定的時間自行返回。
TERMINATED:終止?fàn)顟B(tài),當(dāng)前線程執(zhí)行完畢。
為了更好的理解線程的生命周期,以及生命周期中的各個狀態(tài),接下來使用代碼示例來輸出線程的每個狀態(tài)信息。
WaitingTime
創(chuàng)建WaitingTime類,在while(true)循環(huán)中調(diào)用TimeUnit.SECONDS.sleep(long)方法來驗證線程的TIMED_WARTING狀態(tài),代碼如下所示。
package io.binghe.concurrent.executor.state; import java.util.concurrent.TimeUnit; /** * @author binghe * @version 1.0.0 * @description 線程不斷休眠 */ public class WaitingTime implements Runnable{ @Override public void run() { while (true){ waitSecond(200); } } //線程等待多少秒 public static final void waitSecond(long seconds){ try { TimeUnit.SECONDS.sleep(seconds); } catch (InterruptedException e) { e.printStackTrace(); } } }
創(chuàng)建WaitingState類,此線程會在一個while(true)循環(huán)中,獲取當(dāng)前類Class對象的synchronized鎖,也就是說,這個類無論創(chuàng)建多少個實例,synchronized鎖都是同一個,并且線程會處于等待狀態(tài)。接下來,在synchronized中使用當(dāng)前類的Class對象的wait()方法,來驗證線程的WAITING狀態(tài),代碼如下所示。
package io.binghe.concurrent.executor.state; /** * @author binghe * @version 1.0.0 * @description 線程在Warting上等待 */ public class WaitingState implements Runnable { @Override public void run() { while (true){ synchronized (WaitingState.class){ try { WaitingState.class.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
BlockedThread主要是在synchronized代碼塊中的while(true)循環(huán)中調(diào)用TimeUnit.SECONDS.sleep(long)方法來驗證線程的BLOCKED狀態(tài)。當(dāng)啟動兩個BlockedThread線程時,首先啟動的線程會處于TIMED_WAITING狀態(tài),后啟動的線程會處于BLOCKED狀態(tài)。代碼如下所示。
package io.binghe.concurrent.executor.state; /** * @author binghe * @version 1.0.0 * @description 加鎖后不再釋放鎖 */ public class BlockedThread implements Runnable { @Override public void run() { synchronized (BlockedThread.class){ while (true){ WaitingTime.waitSecond(100); } } } }
啟動各個線程,驗證各個線程輸出的狀態(tài),代碼如下所示。
package io.binghe.concurrent.executor.state; /** * @author binghe * @version 1.0.0 * @description 線程的各種狀態(tài),測試線程的生命周期 */ public class ThreadState { public static void main(String[] args){ new Thread(new WaitingTime(), "WaitingTimeThread").start(); new Thread(new WaitingState(), "WaitingStateThread").start(); //BlockedThread-01線程會搶到鎖,BlockedThread-02線程會阻塞 new Thread(new BlockedThread(), "BlockedThread-01").start(); new Thread(new BlockedThread(), "BlockedThread-02").start(); } }
運行ThreadState類,如下所示。
可以看到,未輸出任何結(jié)果信息。可以在命令行輸入“jps”命令來查看運行的Java進程。
c:\>jps 21584 Jps 17828 KotlinCompileDaemon 12284 Launcher 24572 28492 ThreadState
可以看到ThreadSate進程的進程號為28492,接下來,輸入“jstack 28492”來查看ThreadSate進程棧的信息,如下所示。
c:\>jstack 28492 2020-02-15 00:27:08 Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.202-b08 mixed mode): "DestroyJavaVM" #16 prio=5 os_prio=0 tid=0x000000001ca05000 nid=0x1a4 waiting on condition [0x0000000000000000] java.lang.Thread.State: RUNNABLE "BlockedThread-02" #15 prio=5 os_prio=0 tid=0x000000001ca04800 nid=0x6eb0 waiting for monitor entry [0x000000001da4f000] java.lang.Thread.State: BLOCKED (on object monitor) at io.binghe.concurrent.executor.state.BlockedThread.run(BlockedThread.java:28) - waiting to lock <0x0000000780a7e4e8> (a java.lang.Class for io.binghe.concurrent.executor.state.BlockedThread) at java.lang.Thread.run(Thread.java:748) "BlockedThread-01" #14 prio=5 os_prio=0 tid=0x000000001ca01800 nid=0x6e28 waiting on condition [0x000000001d94f000] java.lang.Thread.State: TIMED_WAITING (sleeping) at java.lang.Thread.sleep(Native Method) at java.lang.Thread.sleep(Thread.java:340) at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386) at io.binghe.concurrent.executor.state.WaitingTime.waitSecond(WaitingTime.java:36) at io.binghe.concurrent.executor.state.BlockedThread.run(BlockedThread.java:28) - locked <0x0000000780a7e4e8> (a java.lang.Class for io.binghe.concurrent.executor.state.BlockedThread) at java.lang.Thread.run(Thread.java:748) "WaitingStateThread" #13 prio=5 os_prio=0 tid=0x000000001ca06000 nid=0x6fe4 in Object.wait() [0x000000001d84f000] java.lang.Thread.State: WAITING (on object monitor) at java.lang.Object.wait(Native Method) - waiting on <0x0000000780a7b488> (a java.lang.Class for io.binghe.concurrent.executor.state.WaitingState) at java.lang.Object.wait(Object.java:502) at io.binghe.concurrent.executor.state.WaitingState.run(WaitingState.java:29) - locked <0x0000000780a7b488> (a java.lang.Class for io.binghe.concurrent.executor.state.WaitingState) at java.lang.Thread.run(Thread.java:748) "WaitingTimeThread" #12 prio=5 os_prio=0 tid=0x000000001c9f8800 nid=0x3858 waiting on condition [0x000000001d74f000] java.lang.Thread.State: TIMED_WAITING (sleeping) at java.lang.Thread.sleep(Native Method) at java.lang.Thread.sleep(Thread.java:340) at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386) at io.binghe.concurrent.executor.state.WaitingTime.waitSecond(WaitingTime.java:36) at io.binghe.concurrent.executor.state.WaitingTime.run(WaitingTime.java:29) at java.lang.Thread.run(Thread.java:748) "Service Thread" #11 daemon prio=9 os_prio=0 tid=0x000000001c935000 nid=0x6864 runnable [0x0000000000000000] java.lang.Thread.State: RUNNABLE "C1 CompilerThread3" #10 daemon prio=9 os_prio=2 tid=0x000000001c88c800 nid=0x6a28 waiting on condition [0x0000000000000000] java.lang.Thread.State: RUNNABLE "C2 CompilerThread2" #9 daemon prio=9 os_prio=2 tid=0x000000001c880000 nid=0x6498 waiting on condition [0x0000000000000000] java.lang.Thread.State: RUNNABLE "C2 CompilerThread1" #8 daemon prio=9 os_prio=2 tid=0x000000001c87c000 nid=0x693c waiting on condition [0x0000000000000000] java.lang.Thread.State: RUNNABLE "C2 CompilerThread0" #7 daemon prio=9 os_prio=2 tid=0x000000001c87b800 nid=0x5d00 waiting on condition [0x0000000000000000] java.lang.Thread.State: RUNNABLE "Monitor Ctrl-Break" #6 daemon prio=5 os_prio=0 tid=0x000000001c862000 nid=0x6034 runnable [0x000000001d04e000] java.lang.Thread.State: RUNNABLE at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.socketRead(SocketInputStream.java:116) at java.net.SocketInputStream.read(SocketInputStream.java:171) at java.net.SocketInputStream.read(SocketInputStream.java:141) at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284) at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326) at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178) - locked <0x0000000780b2fd88> (a java.io.InputStreamReader) at java.io.InputStreamReader.read(InputStreamReader.java:184) at java.io.BufferedReader.fill(BufferedReader.java:161) at java.io.BufferedReader.readLine(BufferedReader.java:324) - locked <0x0000000780b2fd88> (a java.io.InputStreamReader) at java.io.BufferedReader.readLine(BufferedReader.java:389) at com.intellij.rt.execution.application.AppMainV2$1.run(AppMainV2.java:64) "Attach Listener" #5 daemon prio=5 os_prio=2 tid=0x000000001c788800 nid=0x6794 waiting on condition [0x0000000000000000] java.lang.Thread.State: RUNNABLE "Signal Dispatcher" #4 daemon prio=9 os_prio=2 tid=0x000000001c7e3800 nid=0x3354 runnable [0x0000000000000000] java.lang.Thread.State: RUNNABLE "Finalizer" #3 daemon prio=8 os_prio=1 tid=0x000000001c771000 nid=0x6968 in Object.wait() [0x000000001cd4f000] java.lang.Thread.State: WAITING (on object monitor) at java.lang.Object.wait(Native Method) - waiting on <0x0000000780908ed0> (a java.lang.ref.ReferenceQueue$Lock) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:144) - locked <0x0000000780908ed0> (a java.lang.ref.ReferenceQueue$Lock) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:165) at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:216) "Reference Handler" #2 daemon prio=10 os_prio=2 tid=0x000000001c770800 nid=0x6590 in Object.wait() [0x000000001cc4f000] java.lang.Thread.State: WAITING (on object monitor) at java.lang.Object.wait(Native Method) - waiting on <0x0000000780906bf8> (a java.lang.ref.Reference$Lock) at java.lang.Object.wait(Object.java:502) at java.lang.ref.Reference.tryHandlePending(Reference.java:191) - locked <0x0000000780906bf8> (a java.lang.ref.Reference$Lock) at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153) "VM Thread" os_prio=2 tid=0x000000001a979800 nid=0x5c2c runnable "GC task thread#0 (ParallelGC)" os_prio=0 tid=0x00000000033b9000 nid=0x4dc0 runnable "GC task thread#1 (ParallelGC)" os_prio=0 tid=0x00000000033ba800 nid=0x6690 runnable "GC task thread#2 (ParallelGC)" os_prio=0 tid=0x00000000033bc000 nid=0x30b0 runnable "GC task thread#3 (ParallelGC)" os_prio=0 tid=0x00000000033be800 nid=0x6f68 runnable "GC task thread#4 (ParallelGC)" os_prio=0 tid=0x00000000033c1000 nid=0x6478 runnable "GC task thread#5 (ParallelGC)" os_prio=0 tid=0x00000000033c2000 nid=0x4fe4 runnable "GC task thread#6 (ParallelGC)" os_prio=0 tid=0x00000000033c5000 nid=0x584 runnable "GC task thread#7 (ParallelGC)" os_prio=0 tid=0x00000000033c6800 nid=0x6988 runnable "VM Periodic Task Thread" os_prio=2 tid=0x000000001c959800 nid=0x645c waiting on condition JNI global references: 12
由以上輸出的信息可以看出:名稱為WaitingTimeThread的線程處于TIMED_WAITING狀態(tài);名稱為WaitingStateThread的線程處于WAITING狀態(tài);名稱為BlockedThread-01的線程處于TIMED_WAITING狀態(tài);名稱為BlockedThread-02的線程處于BLOCKED狀態(tài)。
注意:使用jps結(jié)合jstack命令可以分析線上生產(chǎn)環(huán)境的Java進程的異常信息。
也可以直接點擊IDEA下圖所示的圖表直接打印出線程的堆棧信息。
輸出的結(jié)果信息與使用“jstack 進程號”命令輸出的信息基本一致。
感謝各位的閱讀,以上就是“線程、多線程和線程池的區(qū)別有哪些”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對線程、多線程和線程池的區(qū)別有哪些這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!
當(dāng)前名稱:線程、多線程和線程池的區(qū)別有哪些
當(dāng)前路徑:http://m.newbst.com/article14/iidege.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信小程序、品牌網(wǎng)站制作、網(wǎng)站排名、網(wǎng)站導(dǎo)航、網(wǎng)站內(nèi)鏈、用戶體驗
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)