亲宝软件园·资讯

展开

Java线程生命周期图文详细讲解

健鑫. 人气:0

线程的状态

New

Runnable

Blocked

Waiting

Timed Waiting

Terminated

代码演示

public class NewRunnableTerminated implements Runnable {
    public static void main(String[] args) {
        Thread thread = new Thread(new NewRunnableTerminated());
        // 打印线程状态
        // New
        System.out.println(thread.getState());
        thread.start();
        // Runnable
        System.out.println(thread.getState());
//        try {
//            Thread.sleep(100);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        // Runnable
        System.out.println(thread.getState());
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // TERMINATED
        System.out.println(thread.getState());
    }
    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            System.out.println(i);
        }
    }
}
/*
* NEW
RUNNABLE
RUNNABLE
* TERMINATED
* */
public class BlockWaitingTimedWaiting implements Runnable{
    public static void main(String[] args) {
        BlockWaitingTimedWaiting blockWaitingTimedWaiting = new BlockWaitingTimedWaiting();
        Thread thread1 = new Thread(blockWaitingTimedWaiting);
        thread1.start();
        Thread thread2 = new Thread(blockWaitingTimedWaiting);
        thread2.start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(thread1.getState());
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(thread2.getState());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(thread1.getState());
    }
    @Override
    public void run() {
        syn();
    }
    private synchronized void syn() {
        try {
            Thread.sleep(1000);
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
/*
* TIMED_WAITING
BLOCKED
WAITING
* */

阻塞状态

加载全部内容

相关教程
猜你喜欢
用户评论