当前位置:网站首页>Thread 类的基本用法
Thread 类的基本用法
2022-07-25 06:34:00 【亲爱的小杰】
@[TOC]目录
##Thread 类的基本用法
线程的创建
我们介绍5种创建线程的方法:
方法一:创建一个类,继承Thread类,重写run()方法
注意:我们并不要认为创建好相关的类以后线程就创建好了,我们还需要创建相对应的实例,并且调用start()方法,一个线程才算创建好了,并且启动了。
方法二:创建一个类,并且实现Runnable接口,并且重写run()方法

这种写法的好处是:代码的耦合度降低了
方法三:继承Thread类,以匿名内部类的形式创建
方法四:实现Runnable接口,以匿名内部类的形式创建

方法五:使用lambda表达式来创建线程(推荐使用)
如何获取线程实例
我们在获取实例化对象的时候,我们一般是通过 new 构造方法 的形式来获取对象。所有说,一种很简单获取线程实例的方法是通过 new 构造方法。 但是,我想问的是,我们在创建一个线程类的时候,如何获取该线程的实例。 比较简单使用:Thread.currentThread()就可以了。
线程休眠
线程休眠:在规定的时间内,线程不能运行,直到到达规定的时间才可以运行。
我们通过 Thread.sleep(自己规定的时间(单位是:毫秒(ms)))
这个方法会抛出异常,需要我们手动地解决一下。
线程中断
有的时候,一个进程中多个线程在执行的时候,有的情况下,有的线程需要中断,这里我提供两种线程中断的方法
方法一:自己设置一个公有变量当作一个标识位
方法二:使用Thread自己带的标识位(重点,难点)
情况一:
情况二:
我们可以看出第二种情况线程并没有中断,只是报一个异常然后接着运行
我们要知道interrupt()方法是如何执行
线程的等待
使用方式:Thread对象.join();
我们无法规定线程的开始执行的顺序,但是我们可以通过join()方法规定线程结束的顺序
哪一个线程调用了join方法,其他线程要等待该线程执行完,他们才能结束
例如:我们有线程1,线程2和主线程,我们想让线程一和线程二执行完后,主线程在执行结束
我们有线程1,线程2和主线程,我们想让线程一在线程二前结束,线程二在主线程前结束

边栏推荐
- 健康打卡每日提醒累了?那就让自动化帮你---HiFlow,应用连接自动化助手
- 【transformer】DeiT
- Interlocked atom access series of functions
- Recycleview realizes horizontal sliding of overlapping items
- Seekbar属性参考
- “font/woff“ and “font/woff2“ in file “mime.types“
- Builder pattern
- VB variable types and control statements (basic)
- Memory memory operation function
- Detailed annotation and analysis of start.s of uboot
猜你喜欢

Evolution of coupon architecture under C2B mode

健康打卡每日提醒累了?那就让自动化帮你---HiFlow,应用连接自动化助手

在C# WinForms应用程序中安装,配置和使用MetroFramework

JZ7 重建二叉树

R strange grammar summary

4、 MFC toolbar, runtime class information mechanism, runtime creation mechanism

Download and run the C open source control metroframework demo project
![[C language] in depth understanding of pointers and arrays (phase I)](/img/4b/26cf10baa29eeff08101dcbbb673a2.png)
[C language] in depth understanding of pointers and arrays (phase I)

DOM event type

JZ7 rebuild binary tree
随机推荐
百度希壤首场元宇宙拍卖落槌,陈丹青六幅版画作品全部成交!
Restrict Su command and sudo mechanism to promote nmap and console command netstat
What determines the "personality" of AI robots?
Ant design input search box listens for allowclear event separately
Easy to understand: basic knowledge of MOS tube
Keilc51 usage details (III)
[datawhale202207] reinforcement learning: the foundation of reinforcement learning
Introduction to the usage of explain and the meaning of result field in MySQL
【Jailhouse 文章】Base Architectures for virtual-physical computing(2018)
C#控件开源库:MetroFramework的下载
[C language] document processing and operation
Prevention strategy of Chang'an chain Shuanghua transaction
Mysql database backup and recovery
Builder pattern
Common API of window
Standard C language 89
Some common interview questions about IO stream and string
The LAF protocol elephant of defi 2.0 may be one of the few profit-making means in your bear market
A little consideration of strategic mode
C language -c51 compilation warning "* * * warning l1: unresolved external symbol" and extern