您好,登錄后才能下訂單哦!
本篇文章為大家展示了Java 線程的生命周期有哪些,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
一 代碼
/** * @Title: ThreadStatus.java * @Description: TODO(演示線程的生命狀態) */ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.TimeUnit; public class ThreadStatus { private static Lock lock = new ReentrantLock(); public static void main(String[] args) { new Thread(new TimeWaiting(), "TimeWaitingThread").start(); new Thread(new Waiting(), "WaitingThread").start(); // 使用兩個Blocked線程,一個獲取鎖,一個被阻塞 new Thread(new Blocked(), "BThread-1").start(); new Thread(new Blocked(), "BThread-2").start(); new Thread(new Sync(), "SyncThread-1").start(); new Thread(new Sync(), "SyncThread-2").start(); } //該線程不斷地進入隨眠 static class TimeWaiting implements Runnable { public void run() { while (true) { try { TimeUnit.SECONDS.sleep(5); System.out.println("I am TimeWaiting Thread: "+ Thread.currentThread().getName()); } catch (InterruptedException e) { } } } } //該線程在Waiting.class實例上等待 static class Waiting implements Runnable { public void run( ) { while (true) { synchronized (Waiting.class) { try { System.out.println("I am Waiting Thread: "+ Thread.currentThread().getName()); Waiting.class.wait( ); } catch (InterruptedException e) { e.printStackTrace( ); } } } } } //該線程在Blocked.class實例上加鎖后,不會釋放該鎖 static class Blocked implements Runnable { public void run( ) { synchronized (Blocked.class) { while (true) { try { System.out.println("I am Blocked Thread: "+ Thread.currentThread().getName()); TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) {} } } } } //該線程用于同步鎖 static class Sync implements Runnable { public void run( ) { lock.lock( ); try { System.out.println("I am Sync Thread: "+ Thread.currentThread().getName()); TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { } finally { lock.unlock(); } } } }
二 運行
I am Waiting Thread: WaitingThread
I am Blocked Thread: BThread-1
I am Sync Thread: SyncThread-1
I am TimeWaiting Thread: TimeWaitingThread
I am Blocked Thread: BThread-1
I am Sync Thread: SyncThread-2
I am TimeWaiting Thread: TimeWaitingThread
I am Blocked Thread: BThread-1
I am TimeWaiting Thread: TimeWaitingThread
I am Blocked Thread: BThread-1
I am TimeWaiting Thread: TimeWaitingThread
I am Blocked Thread: BThread-1
I am TimeWaiting Thread: TimeWaitingThread
I am Blocked Thread: BThread-1
I am TimeWaiting Thread: TimeWaitingThread
I am Blocked Thread: BThread-1
I am TimeWaiting Thread: TimeWaitingThread
I am Blocked Thread: BThread-1
I am TimeWaiting Thread: TimeWaitingThread
I am Blocked Thread: BThread-1
上述內容就是Java 線程的生命周期有哪些,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。