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();
}
}