java并发编程(二) 线程的6种状态

一、线程的状态

  1. 初始(NEW):新创建了一个线程对象,但还没有调用start()方法。
  2. 运行(RUNNABLE):Java线程中将就绪(ready)和运行中(running)两种状态笼统的称为“运行”。
    线程对象创建后,其他线程(比如main线程)调用了该对象的start()方法。该状态的线程位于可运行线程池中,等待被线程调度选中,获取CPU的使用权,此时处于就绪状态(ready)。就绪状态的线程在获得CPU时间片后变为运行中状态(running)。
  3. 阻塞(BLOCKED):表示线程阻塞于锁。
  4. 等待(WAITING):进入该状态的线程需要等待其他线程做出一些特定动作(通知或中断)。
  5. 超时等待(TIMED_WAITING):该状态不同于WAITING,它可以在指定的时间后自行返回。
  6. 终止(TERMINATED):表示该线程已经执行完毕。
public enum State {
        NEW,
        RUNNABLE,
        BLOCKED,
        WAITING,
        TIMED_WAITING,
        TERMINATED;
    }

二、线程状态切换

图片.png

三、线程的六种状态切换代码示例

package com.learn.thread.learn01;

import lombok.extern.slf4j.Slf4j;

import static java.lang.Thread.sleep;

/**
 * @author: lipei
 * @Date:2020/5/5 9:29 下午
 */
@Slf4j
public class ThreadSixTest {
    public static void main(String[] args){
        // 01 -NEW
        Thread thread01 = new Thread(() -> {
            try {
                sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread01.setName("thread01");

        // 02 - RUNNABLE 或RUNNING
        Thread thread02 = new Thread(() -> {
            while (true) {
            }
        });
        thread02.setName("thread02");
        thread02.start();

        // 03 - TIMED_WAITING
        Thread thread03 = new Thread(() -> {
            synchronized (ThreadSixTest.class) {
                try {
                    sleep(100000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                while (true) {
                }
            }

        });
        thread03.setName("thread03");
        thread03.start();

        // 04 TERMINATED
        Thread thread04 = new Thread(() -> {
        });
        thread04.setName("thread04");
        thread04.start();

        // 05-BLOCKED, 等待03释放资源 ThreadSixTest
        Thread thread05 = new Thread(() -> {
            synchronized (ThreadSixTest.class) {
                try {

                    Thread.sleep(200000);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                while (true) {
                }
            }

        });
        thread05.setName("thread05");
        thread05.start();
        
        // 06-WAITING, 等待其它线程
        Thread thread06 = new Thread(() -> {
            try {
                thread05.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread06.setName("thread06");
        thread06.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("thread01 status ={}", thread01.getState());
        log.info("thread02 status ={}", thread02.getState());
        log.info("thread03 status ={}", thread03.getState());
        log.info("thread04 status ={}", thread04.getState());
        log.info("thread05 status ={}", thread05.getState());
        log.info("thread06 status ={}", thread06.getState());
    }
}
  • 控制台输出
21:54:42.788 [main] INFO com.learn.thread.learn01.ThreadSixTest - thread01 status =NEW
21:54:42.802 [main] INFO com.learn.thread.learn01.ThreadSixTest - thread02 status =RUNNABLE
21:54:42.802 [main] INFO com.learn.thread.learn01.ThreadSixTest - thread03 status =TIMED_WAITING
21:54:42.802 [main] INFO com.learn.thread.learn01.ThreadSixTest - thread04 status =TERMINATED
21:54:42.802 [main] INFO com.learn.thread.learn01.ThreadSixTest - thread05 status =BLOCKED
21:54:42.802 [main] INFO com.learn.thread.learn01.ThreadSixTest - thread06 status =WAITING

四、线程切换易考知识点

4.1 调用 Thread start 方法和run 方法有什么区别?

a、在main方法中执行的run()方法不会创建新的线程,而在main方法中执行的start()方法会启动一个新的线程,新的线程会调用run方法
b、run方法可以多次执行,但是start方法不允许多次执行,多次执行start()方法会抛出一个一个运行时异常java.lang.IllegalThreadStateException

4.2 线程让步(yield)和线程睡眠(sleep)区别

  • Sleep

让当前正在执行的线程暂停一段时间,并进入阻塞状态,则可以通过调用Thread类的静态sleep()方法来实现。当前线程调用sleep()方法进入阻塞状态后,在其睡眠时间内,该线程不会获得执行的机会,而其它任何优先级的线程都可以得到执行的机会,即使系统中没有其它可执行的线程,处于sleep()的线程也不会执行,sleep()是用来暂停线程的执行。

  • yield

yield()方法可以让当前正在执行的线程暂停,但它不会阻塞该线程,只是将该线程转入就绪状态。yeild()只是让当前线程暂停一下,让系统的线程调度器重新调度一次,完全可能的情况是:当某个线程调用了yield()线程暂停之后,线程调度器又将其调度出来重新执行。
当某个线程调用了yield()方法暂停之后,只有优先级与当前线程相同,或者优先级比当前线程更高的处于就绪状态的线程才会获得执行机会。

  • 总结

sleep阻塞当前线程,让其它线程运行。yield暂停挂起一下,让位给优先级更高或和自身优先级相同的线程执行。

4.3 JAVA 8 Fork Join框架

4.3.1 JAVA 8 Fork Join框架 简介

Fork/Join框架:在必要的情况下,将一个大任务,进行拆分(fork) 成若干个子任务(拆到不能再拆,这里就是指我们制定的拆分的临界值),再将一个个小任务的结果进行join汇总。

图片.png
  • Fork/Join与传统线程池的区别

Fork/Join采用“工作窃取模式”,当执行新的任务时他可以将其拆分成更小的任务执行,并将小任务加到线程队列中,然后再从一个随即线程中偷一个并把它加入自己的队列中。
就比如两个CPU上有不同的任务,这时候A已经执行完,B还有任务等待执行,这时候A就会将B队尾的任务偷过来,加入自己的队列中,对于传统的线程,ForkJoin更有效的利用的CPU资源!

  • 实现这个框架需要继承RecursiveTask 或者 RecursiveAction ,RecursiveTask是有返回值的,相反Action则没有

4.3.2 无返回值RecursiveAction

  • RecursiveAction, getResult 是void 型的
public abstract class RecursiveAction extends ForkJoinTask {
    private static final long serialVersionUID = 5232453952276485070L;

    /**
     * The main computation performed by this task.
     */
    protected abstract void compute();

    /**
     * Always returns {@code null}.
     *
     * @return {@code null} always
     */
    public final Void getRawResult() { return null; }

    /**
     * Requires null completion value.
     */
    protected final void setRawResult(Void mustBeNull) { }

    /**
     * Implements execution conventions for RecursiveActions.
     */
    protected final boolean exec() {
        compute();
        return true;
    }

}

4.3.3 带泛型返回值RecursiveTask

public abstract class RecursiveTask extends ForkJoinTask {
    private static final long serialVersionUID = 5232453952276485270L;

    /**
     * The result of the computation.
     */
    V result;

    /**
     * The main computation performed by this task.
     * @return the result of the computation
     */
    protected abstract V compute();

    public final V getRawResult() {
        return result;
    }

    protected final void setRawResult(V value) {
        result = value;
    }

    /**
     * Implements execution conventions for RecursiveTask.
     */
    protected final boolean exec() {
        result = compute();
        return true;
    }

}

4.3.4 代码示例

package com.learn.thread.learn01;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.RecursiveTask;

/**
 * @author: lipei
 * @Date:2020/5/5 10:24 下午
 */
@Slf4j
public class ForkJoinTest extends RecursiveTask {
    private static final long serialVersionUID = 4325122569023905605L;

    private Long start;//起始值
    private Long end;//结束值
    public static final  Long critical = 100000L;//临界值

    public static  Long count = 0L;//临界值

    public ForkJoinTest(Long start, Long end) {
        log.info("count ={}", count++);
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        //判断是否是拆分完毕
        Long lenth = end - start;
        if(lenth<=critical){
            //如果拆分完毕就相加
            Long sum = 0L;
            for (Long i = start;i<=end;i++){
                sum += i;
            }
            return sum;
        }else {
            //没有拆分完毕就开始拆分
            Long middle = (end + start)/2;//计算的两个值的中间值
            ForkJoinTest right = new ForkJoinTest(start,middle);
            right.fork();//拆分,并压入线程队列
            ForkJoinTest left = new ForkJoinTest(middle+1,end);
            left.fork();//拆分,并压入线程队列
            //合并
            return right.join() + left.join();
        }
    }

    public static void main(String[] args) {
        ForkJoinTest forkJoinTest = new ForkJoinTest(1L, 1000000L);
        log.info("total = {}", forkJoinTest.compute());
    }
}

4.4 主线程、守护线程、非守护线程

主线程: main,但不是守护线程。
守护线程: 是指在程序运行的时候在后台提供一种通用服务的线程。如gc。
非守护线程: 也叫用户线程,由用户创建。

  • 关系:

主线程和守护线程一起销毁;
主线程和非守护线程互不影响。
默认情况下启动的线程是用户线程(非守护线程), 通过setDaemon(true)将线程设置成守护线程

代码示例

  • 正常情况 main 线程结束后,子线程仍正常工作
@Slf4j
public class WatchThread {
    public static void main(String[] args) {
        log.info("main start");
        Thread thread = new Thread(()->{
           while (true){
               try {
                   Thread.sleep(2000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               log.info("子线程活动中");
           }
        });

        thread.setName("sub thread");
        thread.start();

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("main end");

    }
}

22:47:24.794 [main] INFO com.learn.thread.learn01.WatchThread - main start
22:47:26.950 [sub thread] INFO com.learn.thread.learn01.WatchThread - 子线程活动中
22:47:28.955 [sub thread] INFO com.learn.thread.learn01.WatchThread - 子线程活动中
22:47:30.955 [sub thread] INFO com.learn.thread.learn01.WatchThread - 子线程活动中
22:47:32.957 [sub thread] INFO com.learn.thread.learn01.WatchThread - 子线程活动中
22:47:34.950 [main] INFO com.learn.thread.learn01.WatchThread - main end
22:47:34.959 [sub thread] INFO com.learn.thread.learn01.WatchThread - 子线程活动中
22:47:36.959 [sub thread] INFO com.learn.thread.learn01.WatchThread - 子线程活动中
22:47:38.960 [sub thread] INFO com.learn.thread.learn01.WatchThread - 子线程活动中
  • 设置成守护线程后,主线程结束后,守护线程结束
@Slf4j
public class WatchThread {
    public static void main(String[] args) {
        log.info("main start");
        Thread thread = new Thread(()->{
           while (true){
               try {
                   Thread.sleep(2000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               log.info("子线程活动中");
           }
        });

        thread.setName("sub thread");
        //设置成守护线程
        thread.setDaemon(true);
        thread.start();

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("main end");

    }
}
  • 控制台输出
22:49:25.577 [main] INFO com.learn.thread.learn01.WatchThread - main start
22:49:27.700 [sub thread] INFO com.learn.thread.learn01.WatchThread - 子线程活动中
22:49:29.704 [sub thread] INFO com.learn.thread.learn01.WatchThread - 子线程活动中
22:49:31.709 [sub thread] INFO com.learn.thread.learn01.WatchThread - 子线程活动中
22:49:33.711 [sub thread] INFO com.learn.thread.learn01.WatchThread - 子线程活动中
22:49:35.697 [main] INFO com.learn.thread.learn01.WatchThread - main end

Process finished with exit code 0

参考博客:
https://blog.csdn.net/pange1991/article/details/53860651
https://blog.csdn.net/tianmlin1/article/details/79054304
https://blog.csdn.net/qq_38261174/article/details/81364616
https://www.cnblogs.com/wzqjy/p/7921063.html

你可能感兴趣的:(java并发编程(二) 线程的6种状态)