首页 > 编程语言 >Java的六种线程状态及代码示例

Java的六种线程状态及代码示例

时间:2024-04-19 10:44:36浏览次数:36  
标签:Java Thread 示例 InterruptedException t1 WAITING 线程 new sleep

Java的线程有6个状态,分别是

NEW                      新建状态。刚new出来的thread,还没有调用start,就是这个状态

RUNNABLE          运行状态(分为运行中和就绪)。正在运行,或者等待CPU调度,调用完start,就是这个状态

BLOCKED             阻塞状态。还未竞争到的锁的阻塞在那的情况,使用synchronize,但是还没竞争到锁

WAITING               等待状态。使用wait、join、park都会进入这个状态

TIMED_WAITING  计时等待状态。使用sleep、wait(时间)、join(时间)、parkNanos、parkUntil都会进入这个状态

TERMINATED       终止状态。正常运行完run方法以后

 

如下是各个状态的转换图

 

可以从源码看到这些枚举值

 

 

如下是为了加深理解,模拟出的线程的各个状态

public class ThreadStateTest {

    public static void main(String[] args) throws InterruptedException {

        NEW_RUNNABLE_TERMINATED();

        BLOCKED_by_synchronized();

        WAITING_by_wait();
        WAITING_by_join();
        WAITING_by_park();

        TIMED_WAITING_by_wait_timeout();
        TIMED_WAITING_by_sleep();
        TIMED_WAITING_by_join_timeout();

        TIMED_WAITING_by_parkUntil();
        TIMED_WAITING_by_parkNanos();
    }

    private static void NEW_RUNNABLE_TERMINATED() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            while(!Thread.currentThread().isInterrupted()) {
                for(long j=0;j<100;j++) {}
            }
        });
        System.out.println("state:" + t1.getState() + "    after new");

        t1.start();
        Thread.sleep(500);
        System.out.println("state:" + t1.getState() + "    after start");
        
        t1.interrupt();
        Thread.sleep(500);
        System.out.println("state:" + t1.getState() + "    after all");
    }




    private static void BLOCKED_by_synchronized() throws InterruptedException {
        Object o1 = new Object();
        Thread t1 = new Thread(() -> {
            synchronized (o1) {
            }
        });
        synchronized (o1) {
            t1.start();
            Thread.sleep(1000);
            System.out.println("state:" + t1.getState() + "    BLOCKED_by_synchronized");
        }
    }

    private static void WAITING_by_wait() throws InterruptedException {
        Object o1 = new Object();
        Thread t1 = new Thread(() -> {
            synchronized (o1) {
                try {
                    o1.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        Thread.sleep(1000);
        System.out.println("state:" + t1.getState() + "    WAITING_by_wait");
        synchronized (o1) {
            o1.notifyAll();
        }
    }

    private static void TIMED_WAITING_by_wait_timeout() throws InterruptedException {
        Object o1 = new Object();
        Thread t1 = new Thread(() -> {
            synchronized (o1) {
                try {
                    o1.wait(2 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        Thread.sleep(500);
        System.out.println("state:" + t1.getState() + "    TIMED_WAITING_by_wait_timeout");
    }

    private static void WAITING_by_join() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                Thread.sleep(2 * 1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        Thread t2 = new Thread(() -> {
            t1.start();
            try {
                t1.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t2.start();
        Thread.sleep(500);
        System.out.println("state:" + t2.getState() + "    WAITING_by_join");
    }

    private static void WAITING_by_park() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            LockSupport.park();
        });
        t1.start();
        Thread.sleep(500);
        System.out.println("state:" + t1.getState() + "    WAITING_by_park");
        Thread.sleep(1000);
        LockSupport.unpark(t1);
    }

    private static void TIMED_WAITING_by_sleep() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                Thread.sleep(2 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t1.start();
        Thread.sleep(500);
        System.out.println("state:" + t1.getState() + "    TIMED_WAITING_by_sleep");
    }

    private static void TIMED_WAITING_by_join_timeout() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                Thread.sleep(4 * 1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        Thread t2 = new Thread(() -> {
            t1.start();
            try {
                t1.join(2 * 1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t2.start();
        Thread.sleep(500);
        System.out.println("state:" + t2.getState() + "    TIMED_WAITING_by_join_timeout");
    }

    private static void TIMED_WAITING_by_parkUntil() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            long nowMills = System.currentTimeMillis();
            LockSupport.parkUntil(2*1000+nowMills);
        });
        t1.start();
        Thread.sleep(500);
        System.out.println("state:" + t1.getState() + "    TIMED_WAITING_by_parkUntil");

    }


    private static void TIMED_WAITING_by_parkNanos() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(2));
        });
        t1.start();
        Thread.sleep(500);
        System.out.println("state:" + t1.getState() + "    TIMED_WAITING_by_parkNanos");

    }
}

  

标签:Java,Thread,示例,InterruptedException,t1,WAITING,线程,new,sleep
From: https://www.cnblogs.com/huainanyin/p/18145300

相关文章

  • Java开发者如何使用RunFlow内置的QLExpress
    本文是为Java开发者写的手册,如果您不是Java开发者可以阅读我们的开发者篇手册,当然如果您感兴趣也可以继续阅读。输入qe进入QLExpress专注模式。执行Java代码比如数学计算:Math.sin(9);执行结果:0.4121184852417566。比如读取系统环境变量:top.myrest.myflow.util.Jackson......
  • 基元线程同步构造
    一、基元(一)概述基元指的是在代码中可以使用的最简单的构造。基元是指编程中最基本、最简单的构造或元素,可以直接在代码中使用。基元通常是编程语言中的原始数据类型或基本操作符,用于构建更复杂的数据结构和算法。举例来说,对于C#编程语言,基元可以包括整型(int)、浮点型(float)......
  • 在 VSCode 中使用正则表达式的示例
    下面是一些在VSCode中使用正则表达式的示例。在某个文件中查找相同的单词假设有一个名为sample.txt的文件,其内容如下:thequickbrownfoxjumpsoverthelazydog.thequickbrowncatjumpsoverthelazydog.thequickredhenjumpsoverthelazydog.我们想要查......
  • JavaScript本地存储的方式有哪些
    Web存储技术1.localStorage特点:长期存储,除非手动删除否则会一直保存在浏览器中,清除缓存或卸载浏览器后消失。存储语法:window.localStorage.setItem(名字,值)获取语法:window.localStorage.getItem(名字)删除语法:window.localStorage.removeItem(名字)作用:删除localStorage......
  • Java BigDecimal出现科学计数法
    JavaBigDecimal出现科学计数法查看BigDecimal的toString()源码,可以发现出现toString()出现科学计数法的原因 privateStringlayoutChars(booleansci){...intcoeffLen=coeff.length-offset;longadjusted=-(long)scale+(coeffLen-1);......
  • java动态代理模式
    Java动态代理模式是Java编程语言中的一种设计模式,它提供了一种在运行时动态创建代理对象的方式。这个模式主要用于实现AOP(面向切面编程)的概念,允许开发者在不修改原有业务逻辑代码的情况下,增加额外的功能,如日志记录、事务管理、权限验证等。在Java中,动态代理模式主要依赖于java.l......
  • pytest多线程运行控制台日志输出异常
    开启多线程后控制台日志显示错误,但是日志文件输出正确百度了一个晚上也没有解决,AI也问不出来解决办法,希望有大佬看到。开启多线程运行用例单独运行只有一个线程【gw1】输出日志信息。【gw2,gw0,gw3】都不能输出日志信息通过main()方式运行,控制台日志信息乱码......
  • JavaScripts浮点数计算问题
    JS数学运算精度问题最近项目上JS做加减乘除这类的运算出现了精度不匹配的问题:例如:0.1+0.2->0.300000000000000040.3-0.2->0.099999999999999980.3*2->0.60.3*0.20.060.3/3->0.09999999999999999Mathjs这个JS库可以解决这类问题:官网链接以下是详细的步骤:终端执......
  • 3.Java基础学习
    Java基础注释单行注释多行注释文档注释publicclassHelloworld{publicstaticvoidmain(String[]args){//单行注释////输出一个HelloworldSystem.out.println("Helloworld");/*多行注释多行注释......
  • Java题目集1-3总结
    (1)前言:第一次大作业的知识点包括类与对象正则表达式以及数组对象和不同类之间的关系;题量较小,难度不大,关键是理清question,test-paper,answer-paper之间的关系。第二次大作业的知识点增加了List,ArrayList,HashMap,三种变长数组的使用,增加了正则表达式的难度,题量增加,难度上升,试卷中的......