JAVA----Thread(2

Thread 提供的属性和方法

目录

  • Thread 提供的属性和方法
    • 一.构造方法
      • 1.Thread() :
      • 2.Thread(Runnable target) :
      • 3.Thread(String name) :
        • main 线程
      • 4.Thread(Runnable target, String name) :
    • 二.属性
        • 1.ID (getId)
        • 2.名称(getName)
        • 3.状态(getState)
        • 4.优先级 (getPriority)
        • 5.是否后台线程 (isDaemon)
        • 6.是否存活(isAlive)
          • isAlive()
        • 7.是否被中断(isUnterrupted)

一.构造方法

1.Thread() :

创建线程对象;

2.Thread(Runnable target) :

使用 Runnable 对象创建线程对象;

3.Thread(String name) :

创建线程对象, 并命名;
起名有一个好处: java 进程运行过程中, 可以通过工具看到每个不同线程的名字.
出现问题时, 更直观的把问题线程和代码关联起来(方便调试),
没起名字, 也有默认名字: Thread-0, Thread-1, Thread-2.

当我们运行此代码

package Thread;
public class Demo1 {public static void main(String[] args) {Thread t = new Thread(()->{while(true){System.out.println("hello");try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}}},"自定义线程");//起名t.start();}
}

打开 jconsole - 线程 可以看见
在这里插入图片描述
但是我们仔细看下, 这里看不见 main 线程了, 此处并不是main线程没有被创建, 而是其执行太快, 结束而销毁了.

main 线程

main 线程是通过 jvm 中通过 C++ 代码创建出来的, 没有通过 java 中的 Thread 类创建, 也就不会重写 run

4.Thread(Runnable target, String name) :

使用 Runnable 对象创建线程对象, 并命名;
同上

[了解] Thread(ThreadGroup group, Runnable target) : 线程可以被用来分组管理, 分好的组进行批量控制;
这种写法在实际开发中更多的被线程池取代了.

二.属性

在这里插入图片描述

1.ID (getId)

是线程的唯一标识, 不同线程 不会重复;
与系统内核的 pcb 的 id 是一一对应但不相同的, 是 jvm 自己搞的一套 id 体系.
java代码无法获取到 pcb 中的 id.

2.名称(getName)

在各种调试工具可用到;

3.状态(getState)

表示线程当前所处的一个情况; (就绪 + 阻塞)

4.优先级 (getPriority)

优先级高的线程理论上更容易被调度到;
有些形同虚设, 优先级还是得看系统调度

5.是否后台线程 (isDaemon)

前台线程 :
此线程不结束, java 进程一定不会结束.(可以有多个, 当最后一个前台线程结束, java进程结束)
在 java 中, main 线程, 就是前台线程. 另外程序员创建出来的线程, 默认情况下都是 前台线程.
后台进程 :
此线程即使继续执行, 也不能阻止 java 进程 结束.(不希望此线程, 影响java进程结束)
可以通过 setDaemon 方法 来把线程设置成 后台线程.
在这里插入图片描述
像上图 jvm 内置线程 就是 后台线程

后台线程比如 有的线程负责 gc(垃圾回收) , gc 是要周期性持续性执行的,不可能主动结束.

栗子

package thread;public class Test {public static void main(String[] args) {Thread t = new Thread(() -> {for (int i = 0; i < 5; i++) {System.out.println("hello thread");try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}}});//设置为后台线程//t.setDaemont.start();}
}

未设置为后台线程输出

hello thread
hello thread
hello thread
hello thread
hello threadProcess finished with exit code 0

只要 t 线程 未结束, 进程不结束.
main 执行完, start结束.

设置为后台进程输出

Process finished with exit code 0

当设置t为后台线程, 只有main是前台线程了,
main执行完 start 就结束了.t 线程没来得及打印.(线程之间是抢占式执行).
大概率是什么也不打印.

若将 setDaemon 放在 start 后将会发生什么

package thread;public class Test {public static void main(String[] args) {Thread t = new Thread(() -> {for (int i = 0; i < 5; i++) {System.out.println("hello thread");try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}}});t.start();//设置为后台线程t.setDaemon(true);}
}
Exception in thread "main" java.lang.IllegalThreadStateExceptionat java.lang.Thread.setDaemon(Thread.java:1359)at thread.Test.main(Test.java:16)
hello thread
hello thread
hello thread
hello thread
hello threadProcess finished with exit code 1

此处发生了报错, 并且设置后台线程未生效.
关于各种属性设置, 都要放在 start 之前

6.是否存活(isAlive)

指的是系统中的线程 (PCB) 是否还存在.(Thread的生命周期)

Thread 对象的生命周期, 和 PCB 的生命周期是不一定完全相同的.

package thread;
public class Test {public static void main(String[] args) {Thread t = new Thread(() -> {          });t.start();Thread.sleep(1000);}
}

因为

  Thread t = new Thread(() -> {});

这个代码已经创建了 Thread 实例, 诞生了Thread对象,
但是, 此时, 内核中的 PCB 没有诞生.

t.start();

这个代码, 才是真正的在系统中创建出线程
PCB 才真正的被创建出来并且加入到链表中.

由于t 线程中什么都没写, 所以t 瞬间结束, 内核中的线程和 pcb 就被销毁了.
但是在 sleep 结束之前, t 引用 指向的 Thread 对象 仍然存在, 并且没有被gc回收.
则会出现, 系统中的线程先结束掉了, 但 t 仍存在.

isAlive()
package thread;
public class Test {public static void main(String[] args) {Thread t = new Thread(() -> {          });t.start();Thread.sleep(1000);System.out.println(t.isAlive());}
}
false
package thread;
public class Test {public static void main(String[] args) throws InterruptedException {Thread t = new Thread(() -> {try {Thread.sleep(2000);} catch (InterruptedException e) {throw new RuntimeException(e);}});t.start();Thread.sleep(1000);System.out.println(t.isAlive());}
}
true
7.是否被中断(isUnterrupted)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/670283.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C++11,{}初始化,initializer_list,decltype,右值引用,类和对象的补充

c98是C标准委员会成立第一年的C标准&#xff0c;C的第一次更新是C03&#xff0c;但由于C03基本上是对C98缺陷的修正&#xff0c;所以一般把C98与C03合并起来&#xff0c;叫做C98/03&#xff1b; 后来原本C委员会更新的速度预计是5年更新一次&#xff0c;但由于C标准委员会的进…

数据库大作业——基于qt开发的图书管理系统(二) 相关表结构的设计

前言 在上一篇文章中。我们完成了Qt环境的安装&#xff0c;同时完成了有关项目需求的分析并绘制了整体的项目架构图&#xff0c;而在图书管理系统中&#xff0c;其实我们主要完成的就是对数据的增删改查&#xff0c;并将这些功能通过信号与槽机制和可视化界面绑定在一起&#…

什么是B2B SaaS公司?

前言 在当今数字化时代&#xff0c;B2B SaaS公司正在以惊人的速度崛起&#xff0c;成为企业界的一股重要力量。但是&#xff0c;对于许多人来说&#xff0c;B2B SaaS究竟是什么&#xff0c;以及它如何影响商业生态&#xff0c;可能还是一片未知。本文将简要介绍B2B SaaS公司的…

K. 子串翻转回文串

给一个串 s  s1s2... sn&#xff0c;你可以选定其一个非空子串&#xff0c;然后将该子串翻转。具体来说&#xff0c;若选定的子串区间为 [l, r]&#xff08;1 ≤ l ≤ r ≤ n&#xff09;&#xff0c;则翻转后该串变为 s1s2... sl - 1srsr - 1... slsr  1... sn…

Golang | Leetcode Golang题解之第70题爬楼梯

题目&#xff1a; 题解&#xff1a; func climbStairs(n int) int {sqrt5 : math.Sqrt(5)pow1 : math.Pow((1sqrt5)/2, float64(n1))pow2 : math.Pow((1-sqrt5)/2, float64(n1))return int(math.Round((pow1 - pow2) / sqrt5)) }

getchar和putchar函数详解

getchar和putchar函数详解 1.getchar函数1.1函数概述1.2函数返回值1.3函数注意事项1.4函数的使用 2.putchar函数2.1函数概述2.2函数返回值2.3函数使用实例 1.getchar函数 1.1函数概述 从一个流中读取一个字符&#xff0c;或者从标准输入中获得一个字符 函数原型&#xff1a; …

统一大型语言模型和知识图谱:路线图

【摘要】 大型语言模型&#xff08;LLM&#xff09;&#xff0c;如ChatGPT和GPT4&#xff0c;由于其涌现能力和泛化性&#xff0c;正在自然语言处理和人工智能领域掀起新的浪潮。然而&#xff0c;LLM是黑箱模型&#xff0c;通常无法捕捉和获取事实知识。相反&#xff0c;知识图…

Flutter笔记:Widgets Easier组件库 - 使用标签(Tag)

Flutter笔记 Widgets Easier组件库 - 使用标签&#xff08;Tag&#xff09; - 文章信息 - Author: 李俊才 (jcLee95) Visit me at CSDN: https://jclee95.blog.csdn.netMy WebSite&#xff1a;http://thispage.tech/Email: 291148484163.com. Shenzhen ChinaAddress of this …

【个人博客搭建】(17)使用FluentValidation 参数校验

FluentValidation 是一个用于 .NET 的开源验证库&#xff0c;它提供了一种流畅的接口和强类型验证规则&#xff0c;使得验证逻辑表达得更加清晰和简洁。&#xff08;Apache-2.0&#xff09; FluentValidation 的主要作用包括&#xff1a; 提高代码可读性&#xff1a;通过使用 F…

【打赏收款收银台多合一支付收款HTML源码】

打赏收款收银台多合一支付收款HTML源码 效果图部分源码领取源码下期更新预报 效果图 部分源码 <!DOCTYPE HTML> <html> <head> <title>打赏台</title> <meta name"keywords" content"收银台,个人收款二维码,支付宝在线收款,微…

PostgreSQL连接拒绝如何解决和排查?

1. 服务器未运行 解决方案&#xff1a;确保 PostgreSQL 服务已启动。在 Linux 上&#xff0c;你可以使用如下命令来检查服务状态&#xff1a;sudo systemctl status postgresql如果服务未运行&#xff0c;使用以下命令启动它&#xff1a;sudo systemctl start postgresql2. Po…

C#图像处理实例1:opencvsharp获取轮廓凸包

在OpenCvSharp中&#xff0c;你可以使用Cv2.ApproxPolyDP函数来获取轮廓的凸包。这个函数使用Douglas-Peucker算法来近似轮廓。 以下是一个简单的例子&#xff0c;展示如何使用OpenCvSharp获取轮廓的凸包&#xff1a; Mat src Cv2.ImRead("保存图像\2.jpg", ImreadM…