当前位置:网站首页>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();
}
}
结果
边栏推荐
- 面试官:设计“抖音”直播功能测试用例吧
- Browser onload event
- Meta公司新探索 | 利用Alluxio数据缓存降低Presto延迟
- 51单片机外设篇:点阵式LCD
- nacos registry
- leetcode每天5题-Day04
- Difference and analysis of CPU usage and load
- Redis集群模式
- [C language] LeetCode26. Delete duplicates in an ordered array && LeetCode88. Merge two ordered arrays
- The company does not pay attention to software testing, and the new Ali P8 has written a test case writing specification for us
猜你喜欢

pytorch基本操作:使用神经网络进行分类任务

复盘:图像饱和度计算公式和图像信噪(PSNR)比计算公式

Shell 脚本不同玩法

【漫画】2021满分程序员行为对照表(最新版)

Automated operation and maintenance tools - ansible, overview, installation, module introduction

goroutine (coroutine) in go language

51 MCU peripherals: DS18B20

MySql copies data from one table to another table

Deep learning - CNN realizes the recognition of MNIST handwritten digits

程序员写PPT的小技巧
随机推荐
C语言中i++和++i在循环中的差异性
软件测试在职2年跳槽4次,你还在怪老板不给你涨薪?
Contents of encoding-indexes.js file printed with Bluetooth:
51 MCU Peripherals: Infrared Communication
Detailed installation and configuration of golang environment
非关系型数据库MongoDB的特点及安装
VMTK环境配置记录
【解决】RESP.app 连接不上redis
Integrate ssm (1)
卸载redis
Automated operation and maintenance tools - ansible, overview, installation, module introduction
配合蓝牙打印的encoding-indexes.js文件内容:
coredns介绍
回文串求解的进阶方法
Use the browser's local storage to realize the function of remembering the user name
The company does not pay attention to software testing, and the new Ali P8 has written a test case writing specification for us
【合集- 行业解决方案】如何搭建高性能的数据加速与数据编排平台
Redis集群模式
Say good woman programmers do testing have an advantage?More than a dozen interview, abuse of cry ~ ~ by the interviewer
51 MCU peripherals: DS18B20