package thread;
public class Test {
/**
* 新創建的線程.
*/
public void NEW(){
Thread thread = new Thread();
System.out.println(thread.getState());//NEW
}
/**
* 正在運行的線程.但是處理器不一定會執行此線程.它現在可能在爭奪.
*/
public void RUNNABLE(){
Thread t =new Thread(new Runnable() {
@Override
public void run() {
while(true);
}
});
t.start();
System.out.println(t.getState());//RUNNABLE
}
/**
* 正在運行的線程,如果碰到了同步鎖,則處於被鎖定狀態
* @throws InterruptedException
*/
public void BLOCKED() throws InterruptedException{
Runnable runnable = new Runnable() {
@Override
public synchronized void run() {
while(true);
}
};
Thread t1 = new Thread(runnable);
t1.start();
Thread t2 = new Thread(runnable);
t2.start();
Thread.sleep(1000);//如果不睡眠,t2還是runnable,只能說main線程運行速度太快了.
System.out.println(t1.getState());//RUNNABLE
System.out.println(t2.getState());//BLOCKED
}
/**
* 等待狀態的線程.
* 當前線程被執行這三個方法會處於等待狀態:
* Object.wait();
* Thread.join();
* LockSupport.park();
* @throws InterruptedException
*/
public void WAITING() throws InterruptedException{
Thread main = Thread.currentThread();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(main.getState());//WAITING
}
});
t1.start();
t1.join();
}
/**
* 有時間限制的等待狀態的線程.
* 當前線程被執行這四個方法會處於有時間限制的等待狀態
* Thread.sleep();
* LockSupport.parkNanos();
* LockSupport.parkUntil();
* Object.wait(long);
* Thread.join(long)
* @throws InterruptedException
*/
public void TIMED_WAITING() throws InterruptedException{
Thread main = Thread.currentThread();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(main.getState());//TIMED_WAITING
}
});
t1.start();
t1.join(3000);
}
/**
* 死亡已經結束的線程
* @throws InterruptedException
*/
public void TERMINATED() throws InterruptedException{
Thread t1 = new Thread();
t1.start();
Thread.sleep(1000);
System.out.println(t1.getState());//TERMINATED
}
public static void main(String[] args) throws InterruptedException {
new Test().TERMINATED();
}
}