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

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.xdnf.cn/news/16922.html

相关文章:

  • 位运算在权限授权中的应用及Vue3实践
  • 深度学习(鱼书)day10--与学习相关的技巧(后两节)
  • 【Python练习】075. 编写一个函数,实现简单的语音识别功能
  • MySQL Undo Log
  • 从零开始设计一个分布式KV存储:基于Raft的协程化实现
  • golang 函数选项模式
  • 手机(电脑)与音响的蓝牙通信
  • Python 实例属性与方法命名冲突:一次隐藏的Bug引发的思考
  • 抽奖系统中 Logback 的日志配置文件说明
  • Easy系列PLC相对运动指令实现定长输送(ST源代码)
  • 长文:Java入门教程
  • 求定积分常用技巧
  • 前端工程化:npmvite
  • 小红书开源dots.ocr:单一视觉语言模型中的多语言文档布局解析
  • CUDA杂记--nvcc使用介绍
  • k8s黑马教程笔记
  • MySQL 索引失效的场景与原因
  • 第二章 矩阵
  • Apple基础(Xcode④-Flutter-Platform Channels)
  • OpenCV轻松入门_面向python(第一章OpenCV入门)
  • 【PDF + ZIP 合并器:把ZIP文件打包至PDF文件中】
  • RabbitMQ面试精讲 Day 8:死信队列与延迟队列实现
  • 反向代理+网关部署架构
  • Flask ORM 模型(轻松版)
  • 如何在不停机的情况下,将MySQL单库的数据迁移到分库分表的架构上?
  • Unity_数据持久化_IXmlSerializable接口
  • 如何解决pip安装报错ModuleNotFoundError: No module named ‘scikit-learn’问题
  • ESP32学习-I2C(IIC)通信详解与实践
  • Azure DevOps — Kubernetes 上的自托管代理 — 第3部分
  • GB 44496-2024《汽车软件升级通用技术要求》对行业从业者的变革性影响