当前位置:网站首页>Thread Basics (1)
Thread Basics (1)
2022-08-02 06:32:00 【who is huang huang】
活动地址:CSDN21天学习挑战赛
一.并发与并行的概念
1.程序:一个固定逻辑与数据的集合就是程序 例如 俄罗斯方块 贪吃蛇
2.cpu:中央处理器 主要用于协调程序与硬件的工作
What is concurrency and parallelism?
Let's first take a picture to understand the concurrency and sum并行的区别吧.
The general explanation is:
并发(Also known as high concurrency):是同一个时间段执行两个,或者more than two programs的,单核cpu交互(The time slice rotation mentioned above is one kind)的执行,由于cpu切换的速度很快,逻辑Concurrency on our tasks is同时执行多个任务,实际上是交替执行.
例子:Two teams of people are cooking dishes at a window.
并行:在同一时刻,Do both or yes多个程序的时候,多核cpu同时执行(Phenomenon computers are multi-corecpu)
例子:Multiple people line up in front of multiple coffee machines.

二.线程与进程
概念:
进程:运行在内存中的程序就是进程.
每个进程都有⼀个独⽴的内存空间,⼀个应⽤程序可以同时运⾏多个进程;进程也是程序的⼀次执⾏过程,是系统运⾏程序的基本单位;系统运⾏⼀个程序即是 ⼀个进程从创建、运⾏到消亡的过程
线程: 通向cpu的执行的路径就是线程.
Threads are further divided into single-threaded and multi-threaded
单线程:只有一条通向cpu的执行的路径
多线程:多条通向cup的执行的路径
注意:
1.A process can contain multiple threads
2.一个线程只能存在一个进程中.
3.The thing that is closed in the task manager is called a process

Flowchart of a multithreaded process running
三. 主线程与子线程

3.1主线程:
主方法中,例如运行mainThe thread of the method function
Responsible for managing child threads,That is, the start of the child thread、挂起、stop and so on
public class HelloWorld {
public static void main(String[] args) {
Thread mainThread = Thread.currentThread();
System.out.println("我是主线程");
}
}
3.2子线程:
It can only be understood as being managed by the main thread,That is, the main thread is responsible for starting,挂起,A stopped thread is a child thread
3.3进程,主线程,Diagram of child threads

四.Three ways to create a thread
4.1 第一种 继承Thread重写run方法
步骤:
1.定义一个类去继承Thread
2.重写run()方法,执行线程的操作
3.Instantiate exclusive to this thread class
4.调用start()方法,开启线程
public class MyThread extends Thread{
@Override
public void run() {
for (int i=1;i<=10;i++){
System.out.println(i);
}
}
}
测试类
public class Testhuang {
public static void main(String[] args) {
//实例化对象
MyThread myThread = new MyThread();
myThread.start();
}
}
输出结果:
4.2第二种 实现Runnable接口
步骤:
1.定义一个类 实现 Runnable
2.实现run()
3.实例化线程对象 Thread 传递一个参数 Runnable 的实现类
4.Call the method to start the thread start()
Thread definition class
public class MyRunnable implements Runnable {
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + i);
}
}
}
测试类
public class Testhuang {
public static void main(String[] args) {
//实例化Runnable对象的实现类
MyRunnable r = new MyRunnable(); //实例化线程类
Thread th = new Thread(r); //开启线程
th.start();
}
}
结果
4.3第三种 实现Callable接口
步骤:
1.定义一个类实现接口 Callable
2.重写call()方法
3.实例化 任务对象 FutureTask 构建一个Callable的实现类
4.实例化线程对象 Thread 构建一个任务对象
5.开启线程
6.调用任务对象的get() 获取其返回值
Implement the thread class
public class MyCallAble implements Callable<Integer> {
@Override
public Integer call() throws Exception {
Integer sum = 0;
for (int i = 0; i <= 100; i++) {
sum += i;
}
return sum;
}
}
测试类
public class Testhuang {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallAble call = new MyCallAble();
FutureTask<Integer> f = new FutureTask<>(call);
Thread t = new Thread(f);
t.start();
Integer c = f.get();
System.out.println(c);
}
}
结果
4.4 The most common way to create threads
使用RunnableAn anonymous inner class to create threads
public class Testhuang {
public static void main(String[] args) {
//第一种方式
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}).start();
//第二种方式
new Thread(){
@Override
public void run(){
System.out.println(Thread.currentThread().getName());
}
}.start();
}
}
结果
4.5 线程调度的方式
线程调度的方式有两种:
1.分配式调度:多个线程执行任务的时间,All are evaluation assignments,The cycle of execution of each thread is the same
2.抢占式调度:线程的优先级越高,获取cpuhigher enforcement power,线程抢到cpu的概率the more,The higher the probability of priority execution,而我们的java中的多线程就是抢占式调度

例子:
创建线程类
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
try {
//sleepThe method is the sleep method,interval here0.1s
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//.getName方法获取当前线程的名称
System.out.println(Thread.currentThread().getName() + "\t" + i);
}
}
}
测试类:
public class Testhuang {
public static void main(String[] args) {
//开启第一个线程
MyThread th1 = new MyThread();
th1.start();
//开启第二个线程
MyThread th2 = new MyThread();
System.out.println(th2);
}
}

4.5线程的内存图

4.7 线程的常见方法
4.7.1 获取线程名
| 方法名 | 作用 |
|---|---|
| public final String getName() | 返回该线程的名称 |
| public static Thread currentThread() | 返回对当前正在执行的线程对象的引用 |
线程创建类
public class MyThread extends Thread {
@Override
public void run(){
for (int i = 0; i < 10; i++) {
System.out.println(getName() + "\t" + i);
}
}
}
测试类
public class Testhuang {
public static void main(String[] args) {
//实例化线程对象
MyThread th = new MyThread();
th.start();
for (int i = 1; i <= 10; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + i);
}
}
}
结果
4.7.2 线程休眠
| 方法名 | 作用 |
|---|---|
| public static void sleep(long millis) | 线程休眠 |
线程创建类
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 60; i >= 1; i--) {
System.out.println("还剩下" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
测试类
public class Testhuang {
public static void main(String[] args) {
//实例化线程对象
MyThread th = new MyThread();
th.start();
}
}
结果

4.7.3 守护线程
| 方法名 | 作用 |
|---|---|
| public final void setDaemon(boolean on) | 设置为守护线程 |
| public final boolean isDaemon() | 测试该线程是否为守护线程 |
线程创建类
public class MyThread extends Thread {
@Override
public void run() {
try {
//休眠五秒
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
OutputStream is = new FileOutputStream("3.txt");
is.write(97);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试类
public class Testhuang {
public static void main(String[] args) {
//实例化线程对象
MyThread my = new MyThread();
//设置为守护线程
my.setDaemon(true);
//获取其状态
System.out.println(my.isDaemon());
my.start();
try {
Thread.sleep(6000);
} catch (
InterruptedException e) {
e.printStackTrace();
}
}
}
结果
Shows that the daemon thread is enabled
4.7.4 设置线程的优先级
4.7.4.1 常量
| 常量名 | 作用 |
|---|---|
| public static final int MAX_PRIORITY | 线程可以具有的最高优先级 |
| public static final int MIN_PRIORITY | 线程可以具有的最低优先级 |
| public static final int NORM_PRIORITY | 分配给线程的默认优先级 |

注意点:
1.线程的
最高优先级是10,最低优先级是1,范围1-10
2.线程优先级越高表示获取cpu执行权越大That is, the higher the probability of being executed,但是并不一定会执行,因为java是抢占式调度
4.7.4.2 方法
| 方法名 | 作用 |
|---|---|
| public final int getPriority() | 返回的是线程的优先级 |
| public final void setPriority(int newPriority) | 更改线程的优先级 |
线程创建类
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.println(getName() + "\t" + i);
}
}
}
测试类
public class Testhuang {
public static void main(String[] args) {
//实例化第一个线程
MyThread t = new MyThread();
t.setPriority(8);
t.start(); //
// 实例化第二个线程
MyThread th = new MyThread();
th.setPriority(Thread.MAX_PRIORITY);
th.start();
}
}
结果
边栏推荐
- 对node工程进行压力测试与性能分析
- classSR论文阅读笔记
- Important concepts of target detection - IOU, receptive field, hole convolution, mAP
- Difference and analysis of CPU usage and load
- 【OpenCV从入门到实践】图像处理技术[像素](全网最详细)
- Automated operation and maintenance tools - ansible, overview, installation, module introduction
- 金山云团队分享 | 5000字读懂Presto如何与Alluxio搭配
- Browser onload event
- How much does a test environment cost? Start with cost and efficiency
- VMTK环境配置记录
猜你喜欢

虚拟现实房产展示系统提前预见未来装修效果

51单片机外设篇:红外通信

About the directory structure of the web application

国际顶会OSDI首度收录淘宝系统论文,端云协同智能获大会主旨演讲推荐

Redis-集群模式(主从复制模式,哨兵模式,集群化模式)

The company does not pay attention to software testing, and the new Ali P8 has written a test case writing specification for us

驱动页面性能优化的3个有效策略

Use the browser's local storage to realize the function of remembering the user name

JUC(二)原子类:CAS、乐观锁、Unsafe和原子类

eggjs controller层调用controller层解决方案
随机推荐
MySql copies data from one table to another table
虚拟现实房产展示系统提前预见未来装修效果
Contents of encoding-indexes.js file printed with Bluetooth:
C language: Check for omissions and fill in vacancies (3)
swinIR论文阅读笔记
flex layout (flexible layout)
机器学习——支持向量机原理
eggjs controller层调用controller层解决方案
TikTok平台的两种账户有什么区别?
国际顶会OSDI首度收录淘宝系统论文,端云协同智能获大会主旨演讲推荐
深度学习——CNN实现MNIST手写数字的识别
软件测试的需求人才越来越多,为什么大家还是不太愿意走软件测试的道路?
6W+字记录实验全过程 | 探索Alluxio经济化数据存储策略
字节面试题:如何保证缓存和数据库的一致性
Constructors, member variables, local variables
VMTK环境配置记录
51 MCU Peripherals: Infrared Communication
国际顶会OSDI首度收录淘宝系统论文,端云协同智能获大会主旨演讲推荐
Integrate ssm (1)
C语言入门实战(13):十进制数转二进制