Java并发之线程状态

线程状态

在这里插入图片描述

新建状态(NEW)

    使用 new 操作符创建一个线程,并且尚未调用 start() 方法,此时线程处在新建状态。

Thread t = new DemoThread();
System.out.println(t.getState());
// output: NEW

可运行状态/就绪状态(RUNNABLE)

    一个新创建的线程并不自动开始运行,要执行线程,必须调用线程的 start() 方法。当线程对象调用 start() 方法即启动了线程,start() 方法创建线程运行的系统资源,并调度线程运行 run() 方法。当start()方法返回后,线程就处于就绪状态。
    处于就绪状态的线程并不一定立即运行 run() 方法,线程还必须同其他线程竞争CPU时间,只有获得CPU时间才可以运行线程。因为在单CPU的计算机系统中,不可能同时运行多个线程,一个时刻仅有一个线程处于运行状态。因此此时可能有多个线程处于就绪状态。对多个处于就绪状态的线程是由Java运行时系统的线程调度程序(thread scheduler)来调度的。

Thread t = new DemoThread();
t.start(); // 启动线程
System.out.println(t.getState());
// output: RUNNABLE

阻塞状态(BLOCKED)

    线程处于阻塞状态时,该线程还没有运行结束,只是暂时让出CPU,让其他处于就绪状态的线程有机会获得CPU使用时间,进入运行状态。

synchronized

    比较经典的就是synchronized关键字,这个关键字修饰的代码块或者方法,均需要获取到对应的锁,在未获取之前,其线程的状态处于BLOCKED,如果线程长时间处于这种状态下,就需要看是否出现死锁的问题。

public class MyThread extends Thread{

    private byte[] lock = new byte[0];

    public MyThread(byte[] lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        synchronized (lock){
            try {
                System.out.println(Thread.currentThread().getName() + " is running.");
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " done.");

        }
    }

    public static void main(String[] args) throws InterruptedException {
        byte[] lock = new byte[0];
        MyThread thread1 = new MyThread(lock);
        thread1.setName("thread1");
        thread1.start();
        MyThread thread2 = new MyThread(lock);
        thread2.setName("thread2");
        thread2.start();
        Thread.sleep(1000);//等一会再检查状态
        System.out.println("thread2 当前状态" + thread2.getState());
    }
    /* output:
     * thread1 is running.
     * thread2 当前状态BLOCKED
     * thread1 done.
     * thread2 is running.
     * thread2 done.
     */
}

等待状态

当执行如下代码的时候,对应的线程会进入到 WAITING 状态

  • Object.wait()
  • Thread.join()
  • LockSupport.park()

Object.wait()

public class MyThread extends Thread{
    private Object lock;

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

    @Override
    public void run() {
        System.out.println("等待进入 synchronized 方法");
        synchronized (lock){
            try {
                System.out.println("调用 wait() 方法,释放锁");
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        byte[] lock = new byte[0];
        MyThread myThread = new MyThread(lock);
        myThread.setName("myThread");
        myThread.start();
        Thread.sleep(100);
        System.out.println("myThread 当前状态 " + myThread.getState());
        synchronized (lock){
            lock.notify(); //notify通知wait的线程
        }
        Thread.sleep(100);
        System.out.println("myThread 当前状态 " + myThread.getState());
    }
    /*
     * 等待进入 synchronized 方法
     * 调用 wait() 方法,释放锁
     * myThread 当前状态 WAITING
     * myThread 当前状态 TERMINATED
     */
}

Thread.join()

public class MyThread extends Thread{
    private Object lock;

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

    @Override
    public void run() {
        System.out.println("thread1 正在执行。");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("thread1 执行完毕。");
    }
}
public class MyOtherThread extends Thread{
    Thread thread;

    public MyOtherThread(Thread thread) {
        this.thread = thread;
    }

    @Override
    public void run() {
        System.out.println("thread2 正在执行。并调用 thread1 的 join() 方法");
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("thread1 执行完毕,thread2 后续代码开始执行。");
        System.out.println("thread2 后续代码执行完毕。");
    }
}
public class Main {
    public static void main(String[] args) throws InterruptedException {
        byte[] lock = new byte[0];
        MyThread thread1 = new MyThread(lock);
        thread1.start();
        MyOtherThread thread2 = new MyOtherThread(thread1);
        thread2.start();
        Thread.sleep(100);
        System.out.println("thread2当前状态为 " + thread2.getState());
    }
    /** output:
     * thread1 正在执行。
     * thread2 正在执行。并调用 thread1 的 join() 方法
     * thread2当前状态为 WAITING
     * thread1 执行完毕。
     * thread1 执行完毕,thread2 后续代码开始执行。
     * thread2 后续代码执行完毕。
     */
}

LockSupport.park()

import java.util.concurrent.locks.LockSupport;

public class MyThread extends Thread{
    private Object lock;

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

    @Override
    public void run() {
        System.out.println("调用 LockSupport.park()");
        LockSupport.park();
    }

    public static void main(String[] args) throws InterruptedException {
        byte[] lock = new byte[0];
        MyThread thread = new MyThread(lock);
        thread.start();
        Thread.sleep(100);
        System.out.println("thread 当前状态为 " + thread.getState());
        System.out.println("调用 LockSupport.unpark(thread)");
        LockSupport.unpark(thread);
        Thread.sleep(100);
        System.out.println("thread 当前状态为 " + thread.getState());
    }
    /**output:
     * 调用 LockSupport.park()
     * thread 当前状态为 WAITING
     * 调用 LockSupport.unpark(thread)
     * thread 当前状态为 TERMINATED
     */
}

计时等待状态(TIMED_WAITING)

    TIMED_WAITING 和 WAITING 状态的区别在于,TIMED_WAITING 的等待是有一定时效的,而 WAITING 状态等待的时间是永久的,必须等到某个条件符合才能继续往下走,否则线程不会被唤醒。
    而 TIMED_WAITING,等待一段时间之后,会唤醒线程去重新获取锁。

当执行如下代码的时候,对应的线程会进入到 TIMED_WAITING 状态

  • Thread.sleep(long)
  • Object.wait(long)
  • Thread.join(long)
  • LockSupport.parkNanos()
  • LockSupport.parkUntil()

Thread.sleep(long)

public class MyThread extends Thread{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " 调用 sleep(10000) 方法");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " sleep(10000) 方法执行完毕");
    }
    public static void main(String[] args) throws InterruptedException {
        byte[] lock = new byte[0];
        MyThread myThread = new MyThread();
        myThread.setName("myThread");
        myThread.start();
        Thread.sleep(1000);//等一会再检查状态
        System.out.println("myThread 当前状态" + myThread.getState());
    }
    /* output:
     * myThread 调用 sleep(10000) 方法
     * myThread 当前状态TIMED_WAITING
     * myThread sleep(10000) 方法执行完毕
     */
}

Object.wait(long)

public class MyThread extends Thread{
    private Object lock;

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

    @Override
    public void run() {
        System.out.println("获取锁");
        synchronized (lock){
            try {
                System.out.println("调用 wait(1000) 方法,释放锁");
                lock.wait(1000);//注意,此处1s之后线程醒来,会重新尝试去获取锁,如果拿不到,后面的代码也不执行
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("开始执行 wait() 后续代码");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("后续代码执行完毕");
        }
    }
    public static void main(String[] args) throws InterruptedException {
        byte[] lock = new byte[0];
        MyThread myThread = new MyThread(lock);
        myThread.setName("myThread");
        myThread.start();
        Thread.sleep(100);
        System.out.println("myThread 当前状态 " + myThread.getState());
        Thread.sleep(2000);//等一会再检查状态
        System.out.println("myThread 当前状态 " + myThread.getState());
    }
    /*
     * 获取锁
     * 调用 wait(1000) 方法,释放锁
     * myThread 当前状态 TIMED_WAITING
     * 开始执行 wait() 后续代码
     * 后续代码执行完毕
     * myThread 当前状态 TERMINATED
     */
}

终止状态(TERMINATED)

  • run() 方法运行结束
  • 出现未捕获异常导致 run() 方法异常终止
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值