執行緒,有時稱為輕量級進程(Lightweight Process,LWP),是程式執行流程的最小單元。 一個標準的執行緒由執行緒ID,目前指令指標(PC),暫存器集合和堆疊組成。 如果沒有明確的協同機制,則執行緒將彼此獨立執行。每一個程式都至少有一個線程,若程式只有一個線程,那就是程式本身。
線程是進程中的一個實體,是被系統獨立調度和分派的基本單位,線程自己不擁有系統資源,只擁有一點兒在運作中必不可少的資源,但它可與同屬一個進程的其它線程共享進程所擁有的全部資源(共享進程的內存地址空間),因此這些線程都能訪問相同的變量並在同一個堆上分配對象,這就需要實現一種比在進程間共享資料粒度更細的資料共享機制。如果沒有這種同步機制,在多執行緒的情況下會出現無法預料的後果。
一個執行緒可以建立並撤銷另一個執行緒,同一行程中的多個執行緒之間可以並發執行。由於執行緒之間的相互制約,致使執行緒在運行中呈現出間斷性。線程也有就緒、阻斷和運行三種基本狀態。就緒狀態是指執行緒具備運作的所有條件,邏輯上可以運行,在等待處理機;運作狀態是指執行緒佔有處理機正在運作;阻塞狀態是指執行緒在等待一個事件(如某個訊號量),邏輯上不可執行。
執行緒是程式中單一的順序控制流程。進程內一個相對獨立的、可調度的執行單元,是系統獨立調度和分派CPU的基本單位指運作中的程式的調度單位。在單一程式中同時執行多個執行緒完成不同的工作,稱為多執行緒。
一個Java程式的入口是main方法,透過呼叫main方法開始執行,然後依照程式碼邏輯執行,看似沒有其他執行緒參與,其實java程式天生就是多執行緒程序,執行一個main方法其實就是一個名為mian的執行緒和其他執行緒分別執行,參考程式碼如下:
package com.sunld;import java.lang.management.ManagementFactory;import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean;/** * @Title: TestMainThread.java * @Package com.sunld * <p>Description:</p> * @author sunld * @version V1.0.0 * <p>CreateDate:2017年9月28日 下午3:54:19</p> */public class TestMainThread { public static void main(String[] args) { // 获取Java线程管理MXBean ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); // 不需要获取同步的monitor和synchronizer信息,仅获取线程和线程堆栈信息 ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(false, false); // 遍历线程信息,仅打印线程ID和线程名称信息 for (ThreadInfo threadInfo : threadInfos) { System.out.println("[" + threadInfo.getThreadId() + "] " + threadInfo.getThreadName()); } } }
[5] Attach Listener//附加监听 [4] Signal Dispatcher//分发处理发送给JVM信号的线程 [3] Finalizer//调用对象finalize方法的线程 [2] Reference Handler清除Reference的线程 [1] mainmain线程,用户程序入口
/** * A thread state. A thread can be in one of the following states: * <ul> * <li>{@link #NEW}<br> * A thread that has not yet started is in this state. * </li> * <li>{@link #RUNNABLE}<br> * A thread executing in the Java virtual machine is in this state. * </li> * <li>{@link #BLOCKED}<br> * A thread that is blocked waiting for a monitor lock * is in this state. * </li> * <li>{@link #WAITING}<br> * A thread that is waiting indefinitely for another thread to * perform a particular action is in this state. * </li> * <li>{@link #TIMED_WAITING}<br> * A thread that is waiting for another thread to perform an action * for up to a specified waiting time is in this state. * </li> * <li>{@link #TERMINATED}<br> * A thread that has exited is in this state. * </li> * </ul> * * <p> * A thread can be in only one state at a given point in time. * These states are virtual machine states which do not reflect * any operating system thread states. * * @since 1.5 * @see #getState */ public enum State { /** * Thread state for a thread which has not yet started. */ NEW, /** * Thread state for a runnable thread. A thread in the runnable * state is executing in the Java virtual machine but it may * be waiting for other resources from the operating system * such as processor. */ RUNNABLE, /** * Thread state for a thread blocked waiting for a monitor lock. * A thread in the blocked state is waiting for a monitor lock * to enter a synchronized block/method or * reenter a synchronized block/method after calling * {@link Object#wait() Object.wait}. */ BLOCKED, /** * Thread state for a waiting thread. * A thread is in the waiting state due to calling one of the * following methods: * <ul> * <li>{@link Object#wait() Object.wait} with no timeout</li> * <li>{@link #join() Thread.join} with no timeout</li> * <li>{@link LockSupport#park() LockSupport.park}</li> * </ul> * * <p>A thread in the waiting state is waiting for another thread to * perform a particular action. * * For example, a thread that has called <tt>Object.wait()</tt> * on an object is waiting for another thread to call * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on * that object. A thread that has called <tt>Thread.join()</tt> * is waiting for a specified thread to terminate. */ WAITING, /** * Thread state for a waiting thread with a specified waiting time. * A thread is in the timed waiting state due to calling one of * the following methods with a specified positive waiting time: * <ul> * <li>{@link #sleep Thread.sleep}</li> * <li>{@link Object#wait(long) Object.wait} with timeout</li> * <li>{@link #join(long) Thread.join} with timeout</li> * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li> * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li> * </ul> */ TIMED_WAITING, /** * Thread state for a terminated thread. * The thread has completed execution. */ TERMINATED; }
運行狀態轉換為就緒狀態:當此執行緒主動呼叫yield()方法或在執行過程中失去處理器資源。
運行狀態轉換為死亡狀態:當此執行緒執行體執行完畢或發生了異常。
此處需要特別注意的是:當呼叫執行緒的yield()方法時,執行緒從運行狀態轉換為就緒狀態,但接下來CPU調度就緒狀態中的哪個執行緒具有一定的隨機性,因此,可能會出現A執行緒呼叫了yield()方法後,接下來CPU仍然調度了A執行緒的狀況。
不在執行run方法)在後續的文章中會介紹如何安全的終止一個線程。 。
狀態分析–jvisualvm程式碼-參考(java並發程式設計藝術)package com.sunld; import java.util.concurrent.TimeUnit;/** * @Title: TestThreadState.java * @Package com.sunld * <p>Description:</p> * @author sunld * @version V1.0.0 * <p>CreateDate:2017年9月28日 下午5:14:27</p> */public class TestThreadState { public static void main(String[] args) { new Thread(new TimeWaiting (), "TimeWaitingThread").start(); new Thread(new Waiting(), "WaitingThread").start(); // 使用两个Blocked线程,一个获取锁成功,另一个被阻塞 new Thread(new Blocked(), "BlockedThread-1").start(); new Thread(new Blocked(), "BlockedThread-2").start(); } //该线程不断地进行睡眠 static class TimeWaiting implements Runnable{ @Override public void run() { SleepUtils.second(100); } } //该线程在Waiting.class实例上等待 static class Waiting implements Runnable{ @Override public void run() { while (true) { synchronized (Waiting.class) { try { Waiting.class.wait(); }catch(InterruptedException e) { e.printStackTrace(); } } } } } //该线程在Blocked.class实例上加锁后,不会释放该锁 static class Blocked implements Runnable { @Override public void run() { synchronized (Blocked.class) { while (true) { SleepUtils.second(100); } } } } }class SleepUtils{ public static final void second(long seconds) { try { TimeUnit.SECONDS.sleep(seconds); }catch(InterruptedException e) { e.printStackTrace(); } } }
2017-09-28 17:26:47Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.112-b15 mixed mode): //BlockedThread-2线程获取到了Blocked.class的锁"BlockedThread-2" #13 prio=5 os_prio=0 tid=0x000000001f268000 nid=0x3754 waiting on condition [0x000000002009f000] java.lang.Thread.State: TIMED_WAITING (sleeping) //BlockedThread-1线程阻塞在获取Blocked.class示例的锁上"BlockedThread-1" #12 prio=5 os_prio=0 tid=0x000000001f266800 nid=0x89c waiting for monitor entry [0x000000001ff9f000] java.lang.Thread.State: BLOCKED (on object monitor) //WaitingThread线程在Waiting实例上等待"WaitingThread" #11 prio=5 os_prio=0 tid=0x000000001f260800 nid=0x4d08 in Object.wait() [0x000000001fe9f000] java.lang.Thread.State: WAITING (on object monitor) //TimeWaitingThread线程处于超时等待"TimeWaitingThread" #10 prio=5 os_prio=0 tid=0x000000001f25f000 nid=0x42ac waiting on condition [0x000000001fd9e000] java.lang.Thread.State: TIMED_WAITING (sleeping)
以上是Java並發之線程的使用以及基本概念的詳細內容。更多資訊請關注PHP中文網其他相關文章!