Java线程的生命周期有哪些
本篇文章为大家展示了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 线程的生命周期有哪些,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注创新互联行业资讯频道。
网站名称:Java线程的生命周期有哪些
网站URL:http://ybzwz.com/article/gcecsp.html