一 代码
/**
* @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