Java Thread中的几种状态

java Thread类中定义了线程的六种状态:NEW、RUNNABLE、BLOCKED、WAITING、TIMED_WAITING、TERMINATED

public enum State {
        NEW,
        RUNNABLE,
        BLOCKED,
        WAITING,
        TIMED_WAITING,
        TERMINATED;
    }

- NEW、RUNNABLE、TERMINATED

  1. 新建还没有Start的线程状态为NEW
  2. 线程本身没有被其他线程阻塞,等待cpu调度或者用户io的线程状态为RUNNABLE
  3. 运行结束状态为TERMINATED

示例

public class NewRunAndTerminate {
    public static void main(String args[]) throws InterruptedException {
        Thread firstThread = new TestThread(); //刚创建时是new
        System.out.println(firstThread.getState());
        firstThread.start();
        System.out.println(firstThread.getState());//start 之后是RUNNABLE
        firstThread.join();
        System.out.println(firstThread.getState());//结束后是TERMINATED
    }
}

class TestThread extends Thread {
    @Override
    public void run() {
        System.out.println("Thread start");
        System.out.println("Thread end");
    }
}

运行结果

NEW
RUNNABLE
Thread start
Thread end
TERMINATED

Process finished with exit code 0

- WAITING和TIMED_WAITING

  1. 当线程调用 joinwait 或者 sleep 方法时,状态会变成WAITING或者TIMED_WAITING
  2. WAITING和TIMED_WAITING的区别在于有没有设置超时时间,如果设置了超时时间就是TIMED_WAITING,没设置超时时间就是WAITING

具体可以看以下两个例子:

1)不设超是时间
public class TimeWaitAndWait {
    public static void main(String args[]) throws InterruptedException {
        Object lock = new Object();
        ThreadA a = new ThreadA(lock);
        ThreadB b = new ThreadB(lock);
        a.start();
        Thread.sleep(1000);
        b.start();
       //启动AB两个线程,打印状态
        while (a.isAlive() || b.isAlive()) {
            System.out.println("Thread A:" + a.getState() + ",Thread B:" + b.getState());
            Thread.sleep(500);
        }
    }
}

//线程A
class ThreadA extends Thread {
    private Object lock;
    public ThreadA(Object lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        System.out.println("ThreadA started.");
        synchronized (lock) {
            System.out.println("ThreadA get the lock.");
            try {
                lock.wait(); //wait,等待线程B唤醒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("ThreadA release the lock.");
        System.out.println("ThreadA end.");
    }
}

class ThreadB extends Thread {
    private Object lock;
    public ThreadB(Object lock) {
        this.lock = lock;
    }

    @Override
    public void run()  {
        System.out.println("ThreadB started.");
        synchronized (lock) {
            System.out.println("ThreadB get the lock.");
            try {
                sleep(3000);//拿到锁之后3秒唤醒线程A
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.notify();
        }
        System.out.println("ThreadB release the lock.");
        System.out.println("ThreadB end.");
    }
}

运行结果:

ThreadA started.
ThreadA get the lock.
ThreadB started.
ThreadB get the lock.
Thread A:WAITING,Thread B:TIMED_WAITING
Thread A:WAITING,Thread B:TIMED_WAITING
Thread A:WAITING,Thread B:TIMED_WAITING
Thread A:WAITING,Thread B:TIMED_WAITING
Thread A:WAITING,Thread B:TIMED_WAITING
Thread A:WAITING,Thread B:TIMED_WAITING
ThreadB release the lock.
ThreadB end.
ThreadA release the lock.
ThreadA end.
Process finished with exit code 0

1)首先,线程A先启动,获得lock
2)随后线程A马上调用 wait,释放锁并进入 WAITING 状态
3)线程B获得锁,sleep 3 秒,由于sleep是有时间的,所以B进入TIMED_WAITING状态
4)线程B调用 notify 唤醒线程A,自己运行结束
5)线程A再次获得lock并运行结束

2)设置超时时间

其他部分和上个例子一样,只是线程A的 wait 方法设置成最大等待 2 秒

class ThreadA2 extends Thread {
    private Object lock;
    public ThreadA2(Object lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        System.out.println("ThreadA started.");
        synchronized (lock) {
            System.out.println("ThreadA get the lock.");
            try {
                lock.wait(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("ThreadA release the lock.");
        System.out.println("ThreadA end.");
    }
}

运行结果:

ThreadA started.
ThreadA get the lock.
ThreadB started.
ThreadB get the lock.
ThreadA:TIMED_WAITING,Thread B:TIMED_WAITING
ThreadA:TIMED_WAITING,Thread B:TIMED_WAITING
ThreadA:BLOCKED,Thread B:TIMED_WAITING
ThreadA:BLOCKED,Thread B:TIMED_WAITING
ThreadA:BLOCKED,Thread B:TIMED_WAITING
ThreadA:BLOCKED,Thread B:TIMED_WAITING
ThreadB release the lock.
ThreadB end.
ThreadA release the lock.
ThreadA end.

Process finished with exit code 0

1)线程A先启动,随后调用 wait(2000) 方法进入TIMED_WAITING 状态并释放锁
2)线程B获得锁并调用 sleep 方法,同样进入TIMED_WAITING状态
3)线程A wait 方法超时后尝试重新获得锁,但因为锁被线程B占用,因此线程A进入BLOCKED状态
4)线程B sleep 结束,释放锁并运行结束
5)线程A再次获得锁并运行结束

-WAITING 和 BLOCKED

BLOCKED 与 WAITING 的区别在于BLOCKED是等待锁时的状态

示例:
class ThreadA3 extends Thread {

    private Object lock;

    public ThreadA3(Object lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        System.out.println("ThreadA started.");
        synchronized (lock) {
            System.out.println("ThreadA get the lock.");
            try {
                sleep(3000);
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("ThreadA release the lock.");
        System.out.println("ThreadA end.");
    }
}

class ThreadB3 extends Thread {

    private Object lock;

    public ThreadB3(Object lock) {
        this.lock = lock;
    }

    @Override
    public void run()  {
        System.out.println("ThreadB started.");
        synchronized (lock) {
            System.out.println("ThreadB get the lock.");
            lock.notify();
            try {
                sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("ThreadB release the lock.");
        System.out.println("ThreadB end.");
    }
}

运行结果:

ThreadA started.
ThreadA get the lock.
ThreadB started.
Thread A:TIMED_WAITING,Thread B:BLOCKED
Thread A:TIMED_WAITING,Thread B:BLOCKED
Thread A:TIMED_WAITING,Thread B:BLOCKED
Thread A:TIMED_WAITING,Thread B:BLOCKED
ThreadB get the lock.
Thread A:BLOCKED,Thread B:TIMED_WAITING
Thread A:BLOCKED,Thread B:TIMED_WAITING
Thread A:BLOCKED,Thread B:TIMED_WAITING
Thread A:BLOCKED,Thread B:TIMED_WAITING
Thread A:BLOCKED,Thread B:TIMED_WAITING
Thread A:BLOCKED,Thread B:TIMED_WAITING
ThreadB release the lock.
ThreadB end.
ThreadA release the lock.
ThreadA end.

1)线程A先启动并获得锁,调用sleep 进入TIMED_WAITING状态
2)线程B竞争锁失败,进入 BLOCKED 状态
3)线程A调用wait方法释放锁并等待唤醒
4)线程B获得锁并唤醒线程A,自己进入TIMED_WAITING状态
5)线程A被唤醒后尝试重新获取锁但失败,进入BLOCKED状态
6)线程B结束并释放锁
7)线程A获得锁并结束线程

总结

  1. 新建未start的线程状态为NEW
  2. 调用waitjoin并且没设置超时的线程状态为WAITING
  3. 调用waitjoinsleep并且设置超时的线程状态为TIMED_WAITING
  4. 等待锁的线程状态为BLOCKED
  5. 其他运行中的线程状态为RUNNABLE
  6. 运行结束的线程状态为TERMINATED
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,634评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,951评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,427评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,770评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,835评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,799评论 1 294
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,768评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,544评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,979评论 1 308
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,271评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,427评论 1 345
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,121评论 5 340
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,756评论 3 324
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,375评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,579评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,410评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,315评论 2 352