Flask接口签名sign原理与实例代码浅析
193
2022-12-25
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());
TimijsaxeUnit.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进程与线程操作技巧总结》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~