当前位置: 首页 > news >正文

Thread 类的基本用法

线程创建

优先选择 lambda 表达式

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

线程中断

thread.interrupt();
public static void main(String[] args) {Thread thread = new Thread(() -> {while (!Thread.currentThread().isInterrupted()) {//Thread.currentThread(); -> 获取当前线程引用System.out.println("Hello Thread");try {Thread.sleep(10000);//若阻塞时间过长,即便输入0后也不会立即终止。//必须得等阻塞完之后才会终止执行} catch (InterruptedException e) {// throw new RuntimeException(e);// e.printStackTrace();//不会停止进程  sleep 会清除标志位break;}}});thread.start();Scanner scanner = new Scanner(System.in);System.out.println("按零退出线程");int input = scanner.nextInt();if (input == 0) {thread.interrupt();}}

线程等待

thread.join();

 

public class Demo10 {private static int ret = 0;public static void main(String[] args) {Thread thread = new Thread(() -> {for (int i = 1; i <= 1000; i++) {ret += i;}});thread.start();System.out.println(ret);}
}

此时输出的结果就为 0。因为 thread 线程和 main 线程同时进行导致 main 线程在读取 ret 的值时仍旧为 0 。

解决方法:只需在线程 thread start 之后调用 thread 的 join 方法,此时 main 线程就会排在 thread 线程之后。此时的输出结果即为正常结果。

public class Demo10 {private static int ret = 0;public static void main(String[] args) throws InterruptedException {Thread thread = new Thread(() -> {for (int i = 1; i <= 1000; i++) {ret += i;}});thread.start();thread.join();System.out.println(ret);}
}

线程休眠

Thread.sleep(1000);

 

获取线程实例

    public static void main(String[] args) {Thread t1 = new Thread() {public void run() {//可通过this.getName()获取当前线程名System.out.println(this.getName());}};t1.start();Thread t2 = new Thread(new Runnable() {public void run() {//System.out.println(this.getName());//报错,此时的 this 指代的是 Runnable, 而 Runnable 内没有 getName() 方法//仍需调用用Thread类中的Thread.currentThread()获取当前线程Thread cur = Thread.currentThread();System.out.println(cur.getName());System.out.println(Thread.currentThread().getName());}});t2.start();Thread t3 = new Thread(() -> {//lambda 表达式也是如此,同t2,不支持thisSystem.out.println(Thread.currentThread().getName());});t3.start();}

http://www.dtcms.com/a/312707.html

相关文章:

  • 蛇形卷积介绍
  • Spring Cloud微服务中的内存泄漏问题定位与解决方案
  • 【Unity】背包系统 + 物品管理窗口 (上)
  • 7.13.B+树
  • 【机器学习】线性回归算法详解:线性回归、岭回归、Lasso回归与Elastic Net
  • [AI8051U入门第十四步]W5500实现UDP通信
  • 第六章第三节 TIM 输出比较
  • Baumer工业相机堡盟工业相机如何通过YoloV8深度学习模型实现各类垃圾的分类检测识别(C#代码UI界面版)
  • 学习游戏制作记录(实现克隆攻击的克隆复制和水晶代替克隆)8.3
  • 机器学习——下采样(UnderSampling),解决类别不平衡问题,案例:逻辑回归 信用卡欺诈检测
  • LangChain缓冲记忆组件的使用与解析
  • 决策树学习全解析:从理论到实战
  • 数据结构:在链表中插入节点(Inserting in a Linked List)
  • 回归的wry
  • 浅谈Python中的os.environ:环境变量交互机制
  • Uniapp一根数据线实现真机调试运行【uniapp如何把项目运行在手机上】
  • io_submit系统调用及示例
  • 基于springboot的在线考试系统/考试信息管理平台
  • Suno的100个高质量歌词元标签(MetaTags)详解与使用指南
  • SpringBoot3.x入门到精通系列:2.4 RESTful API设计
  • 电脑声音标志显示红叉的原因
  • Spring Batch的2种STEP定义方式
  • spring-ai-alibaba 学习(二十)——graph之检查点
  • VUE2 学习笔记16 插槽、Vuex
  • 大屏项目展示
  • python学智能算法(三十一)|SVM-Slater条件理解
  • 【MySQL进阶】------MySQL程序
  • 全排列二(回溯算法)
  • 位图:用bit改变存储格局
  • Linux 文件与目录操作命令宝典