当前位置:网站首页>线程基础
线程基础
2022-07-28 02:17:00 【gbk_utf8】
今天这期内容给大家分享一下我在学习线程的时候的一些知识以及线程和进程的区别!
目录
一、基本概念
(一)进程的概念

(二)线程的概念

1、线程的组成
2、线程的基本状态

这里大家注意,图中显示的仅为线程的基本状态。
其实书上写的是线程有五个状态

(1).新建状态(New):
当用new操作符创建一个线程时, 例如new Thread(r),线程还没有开始运行,此时线程处在新建状态。 当一个线程处于新生状态时,程序还没有开始运行线程中的代码
(2).就绪状态(Runnable)
一个新创建的线程并不自动开始运行,要执行线程,必须调用线程的start()方法。当线程对象调用start()方法即启动了线程,start()方法创建线程运行的系统资源,并调度线程运行run()方法。当start()方法返回后,线程就处于就绪状态。
(3).运行状态(Running)
当线程获得CPU时间后,它才进入运行状态,真正开始执行run()方法.
(4). 阻塞状态(Blocked)
线程运行过程中,可能由于各种原因进入阻塞状态:
所谓阻塞状态是正在运行的线程没有运行结束,暂时让出CPU,这时其他处于就绪状态的线程就可以获得CPU时间,进入运行状态。线程通过调用sleep方法进入睡眠状态;
(5). 死亡状态(Dead)
有两个原因会导致线程死亡:
1) run方法正常退出而自然死亡,
2) 一个未捕获的异常终止了run方法而使线程猝死。
二、线程的几种基本创建方式
(一)、继承Thread类
下图为创建线程的方法类(线程里的方法以输出1~5为例)
//第一种方法 继承Thread类
public class MyThread extends Thread{
public void run(){
for(int i=1;i<=5;i++){
System.out.println(Thread.currentThread().getName()+"===========>"+i);
}
}
}
下图为测试类.
public class Demo01 {
public static void main(String[] args) {
Thread t1=new MyThread();
t1.setName("线程1");
t1.start();
Thread t2=new MyThread();
t2.setName("线程2");
t2.start();
}
}(二)、实现Runnable接口
//方式2:实现Runnable接口
public class MyThread1 implements Runnable {
@Override
public void run() {
for(int i=1;i<=5;i++){
System.out.println(Thread.currentThread().getName()+"=======>"+i);
}
}
}测试类:
public class Demo02 {
public static void main(String[] args) {
MyThread1 t=new MyThread1();
Thread t1=new Thread(t,"线程1");
t1.start();
Thread t2=new Thread(t,"线程2");
t2.start();
}
}
(三)实现Callable接口
import java.util.concurrent.Callable;
//方法3:实现Callable接口
public class MyThread3 implements Callable {
int sum=0;
@Override
public Object call() throws Exception {
for(int i=1;i<=5;i++){
sum=sum+i;
}
return sum;
}
}测试类:
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
//实现Callable接口
public class Demo03 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//=======拿到线程的返回 实现CallAble接口========
MyThread3 m=new MyThread3();
FutureTask<Integer> ft=new FutureTask<Integer>(m);
Thread t=new Thread(ft);
t.start();
Integer sum=ft.get();
System.out.println(sum);
}
}
※(四)线程池创建
1、线程池概念
2、线程池原理

其实线程池顾名思义就是事先创建若干个可执行的线程放入一个池(容器)中,需要的时候从池中获取线程不用自行创建,使用完毕不需要销毁线程而是放回池中,从而减少创建和销毁线程对象的开销。
(1)降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的消耗。
(2)提高响应速度。当任务到达时,任务可以不需要等到线程创建就能执行。
(3)提高线程的可管理性,线程是稀缺资源,如果无限制地创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一分配、调优和监控。
3、创建线程池
import java.util.concurrent.Callable;
public class MyThread3 implements Callable {
int sum=0;
@Override
public Object call() throws Exception {
for(int i=0;i<=100;i++){
sum=sum+i;
}
return sum;
}
}
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
public class Demo04 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService pool= Executors.newFixedThreadPool(5);
MyThread3 m=new MyThread3();
FutureTask<Integer> ft = new FutureTask<Integer>(m);
pool.submit(ft);//Thread t1 = new Thread(ft);
Integer res = ft.get();
System.out.println(res);
pool.submit(m);
}
}
运行结果(这四种方法的运行结果是一样的、所以我在这只放一个运行结果的截图)

三、线程跟进程的区别
边栏推荐
- Day 8 of DL
- [stream] parallel stream and sequential stream
- 没法预测明天的涨跌
- Using pytorch's tensorboard visual deep learning indicators | pytorch series (25)
- CNN中的混淆矩阵 | PyTorch系列(二十三)
- Where do I go to open an account for stock speculation? Is it safe to open an account on my mobile phone
- 方案分享 | 高手云集 共同探索重口音AI语音识别
- CSDN TOP1“一个处女座的程序猿“如何通过写作成为百万粉丝博主?
- CNN训练循环重构——超参数测试 | PyTorch系列(二十八)
- 基于JSP&Servlet实现的众筹平台系统
猜你喜欢

RTSP/Onvif协议EasyNVR视频平台一键升级方案的开发设计逻辑

分布式 session 的4个解决方案,你觉得哪个最好?
![[stream] parallel stream and sequential stream](/img/e1/b8728962c14df56241aa6973c0c706.png)
[stream] parallel stream and sequential stream

GAMES101复习:光线追踪(Ray Tracing)

@The function of valid (cascade verification) and the explanation of common constraint annotations

Unexpected harvest of epic distributed resources, from basic to advanced are full of dry goods, big guys are strong!

JS event object 2 e.charcode character code e.keycode key code box moves up, down, left and right
![[wechat applet development (VI)] draw the circular progress bar of the music player](/img/eb/9ce5d196970a6d6a887bf3e1d742ee.png)
[wechat applet development (VI)] draw the circular progress bar of the music player

Docker advanced -redis cluster configuration in docker container
![Trivy [1] tool scanning application](/img/b1/c05949f9379fcde658da64f3a0157a.png)
Trivy [1] tool scanning application
随机推荐
JS 事件对象 offsetX/Y clientX Y PageX Y
优炫数据库客户端如何认证
[brother hero's July training] day 26: check the collection
MySQL索引学习
How do gateways and chirpstacks in lorawan communicate? UDP? GRPC? MQTT?
牛客-TOP101-BM340
Retainface use error: modulenotfounderror: no module named'rcnn.cyton.bbox'
Gbase8s how to delete data in a table with a foreign key relationship
JVM memory layout detailed, illustrated, well written!
为什么登录时,明明使用的是数据库里已经有的账号信息,但依旧显示“用户不存在”?
Intelligent industrial design software company Tianfu C round financing of hundreds of millions of yuan
Building of APP automation environment (I)
P6118 [joi 2019 final] solution to the problem of Zhenzhou City
R 笔记 MICE
Opengauss source code, what ide tools are used to manage, edit and debug?
Trivy [1] tool scanning application
Web服务器
[brother hero's July training] day 27: picture
小程序已获取数据库合集中的总记录、用户位置,怎么用Aggregate.geoNear将经纬度由近到远排列?
Is the securities account given by qiniu safe? Can qiniu open an account and buy funds