Java 线程的生命周期完整实例分析
本文实例讲述了Java线程的生命周期。分享给大家供大家参考,具体如下:
一代码
/** *@Title:ThreadStatus.java *@Description:TODO(演示线程的生命状态) */ importjava.util.concurrent.locks.Lock; importjava.util.concurrent.locks.ReentrantLock; importjava.util.concurrent.TimeUnit; publicclassThreadStatus { privatestaticLocklock=newReentrantLock(); publicstaticvoidmain(String[]args) { newThread(newTimeWaiting(),"TimeWaitingThread").start(); newThread(newWaiting(),"WaitingThread").start(); //使用两个Blocked线程,一个获取锁,一个被阻塞 newThread(newBlocked(),"BThread-1").start(); newThread(newBlocked(),"BThread-2").start(); newThread(newSync(),"SyncThread-1").start(); newThread(newSync(),"SyncThread-2").start(); } //该线程不断地进入随眠 staticclassTimeWaitingimplementsRunnable { publicvoidrun(){ while(true) { try{ TimeUnit.SECONDS.sleep(5); System.out.println("IamTimeWaitingThread:"+Thread.currentThread().getName()); }catch(InterruptedExceptione){} } } } //该线程在Waiting.class实例上等待 staticclassWaitingimplementsRunnable { publicvoidrun() { while(true) { synchronized(Waiting.class) { try{ System.out.println("IamWaitingThread:"+Thread.currentThread().getName()); Waiting.class.wait(); }catch(InterruptedExceptione){ e.printStackTrace(); } } } } } //该线程在Blocked.class实例上加锁后,不会释放该锁 staticclassBlockedimplementsRunnable { publicvoidrun() { synchronized(Blocked.class) { while(true) { try{ System.out.println("IamBlockedThread:"+Thread.currentThread().getName()); TimeUnit.SECONDS.sleep(5); }catch(InterruptedExceptione){} } } } } //该线程用于同步锁 staticclassSyncimplementsRunnable { publicvoidrun(){ lock.lock(); try{ System.out.println("IamSyncThread:"+Thread.currentThread().getName()); TimeUnit.SECONDS.sleep(5); }catch(InterruptedExceptione){} finally{ lock.unlock(); } } } }
二运行
IamWaitingThread:WaitingThread
IamBlockedThread:BThread-1
IamSyncThread:SyncThread-1
IamTimeWaitingThread:TimeWaitingThread
IamBlockedThread:BThread-1
IamSyncThread:SyncThread-2
IamTimeWaitingThread:TimeWaitingThread
IamBlockedThread:BThread-1
IamTimeWaitingThread:TimeWaitingThread
IamBlockedThread:BThread-1
IamTimeWaitingThread:TimeWaitingThread
IamBlockedThread:BThread-1
IamTimeWaitingThread:TimeWaitingThread
IamBlockedThread:BThread-1
IamTimeWaitingThread:TimeWaitingThread
IamBlockedThread:BThread-1
IamTimeWaitingThread:TimeWaitingThread
IamBlockedThread:BThread-1
IamTimeWaitingThread:TimeWaitingThread
IamBlockedThread:BThread-1
更多java相关内容感兴趣的读者可查看本站专题:《Java进程与线程操作技巧总结》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。