当前位置:网站首页>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();
}
}
结果
边栏推荐
- Difference and analysis of CPU usage and load
- 虚拟现实房产展示系统提前预见未来装修效果
- H5 access payment process - WeChat payment & Alipay payment
- Contents of encoding-indexes.js file printed with Bluetooth:
- 51单片机外设篇:红外通信
- 家用 NAS 服务器(4)| MergerFS和SnapRaid数据定时备份
- 线程基础(一)
- How Navicat Connects to MySQL
- nacos注册中心
- Say good woman programmers do testing have an advantage?More than a dozen interview, abuse of cry ~ ~ by the interviewer
猜你喜欢
【解决】RESP.app 连接不上redis
classSR论文阅读笔记
coredns介绍
Introduction to Grid Layout
Shell 脚本不同玩法
goroutine (coroutine) in go language
The company does not pay attention to software testing, and the new Ali P8 has written a test case writing specification for us
The Go language learning notes - dealing with timeout - use the language from scratch from Context
无代码生产新模式探索
机器学习——支持向量机原理
随机推荐
点云旋转到参考坐标系方向(最小方向包围盒方法)
Different ways of shell scripting
Say good woman programmers do testing have an advantage?More than a dozen interview, abuse of cry ~ ~ by the interviewer
Navicat报错:1045 -拒绝访问用户[email protected](使用passwordYES)
Alluxio为Presto赋能跨云的自助服务能力
说好的女程序员做测试有优势?面试十几家,被面试官虐哭~~
C language entry combat (13): decimal number to binary
Difference and analysis of CPU usage and load
Deep learning - CNN realizes the recognition of MNIST handwritten digits
5年在职经验之谈:2年功能测试、3年自动化测试,从入门到不可自拔...
Redis-集群模式(主从复制模式,哨兵模式,集群化模式)
洛谷小游戏大全(用洛谷的人都得知道)
C语言基础知识梳理总结:零基础入门请看这一篇
MySql copies data from one table to another table
Introduction to Grid Layout
Meta公司内部项目-RaptorX:将Presto性能提升10倍
Detailed explanation of interface in Go language
淘系资深工程师整理的300+项学习资源清单(2021最新版)
kubernetes affinity, anti-affinity, taint, tolerance
APP Bluetooth connection test of test technology