Java 基础线程篇

devtools/2025/1/20 5:31:54/

一、线程声明及线程间通信

java">package org.example;import java.util.Random;public class ThreadTest {public void test1() {Thread t1 = new Thread(()->{System.out.println("t1...");});Thread t2 = new Thread(()->{System.out.println("t2...");});// new 线程初始化System.out.println("t1 new:" + t1.getState());t1.start();t2.start();// start 线程执行System.out.println("t1 start:" + t1.getState());}public void  threadBlockTest() {Object obj = new Object();Thread t1 = new Thread(()->{synchronized (obj) {while (true) {System.out.println("t1 lock run ..");try {Thread.sleep(new Random().nextInt(1000));} catch (InterruptedException e) {throw new RuntimeException(e);}}}});Thread t2 = new Thread(()->{synchronized (obj) {System.out.println("t2 lock run ..");}});t1.start();t2.start();System.out.println("t1 status:" + t1.getState());System.out.println("t2 status:" + t2.getState());}public void threadWaitingTest() {Object object = new Object();Thread t1 = new Thread(()->{synchronized (object) {try {System.out.println("t1 start to wait...");object.wait();System.out.println("t1 wait end");} catch (InterruptedException e) {throw new RuntimeException(e);}}});Thread t3 = new Thread(()->{synchronized (object) {try {System.out.println("t3 start to wait...");object.wait();System.out.println("t3 wait end");} catch (InterruptedException e) {throw new RuntimeException(e);}}});Thread t2 = new Thread(()->{synchronized (object) {System.out.println("t2 start ...");int i = 0;while (i<5) {System.out.println("t2 执行次数:" + i);i++;}object.notify();System.out.println("t2 notifyAll");}});t1.start();t2.start();t3.start();System.out.println("t1 state:" + t1.getState());System.out.println("t1 state:" + t1.getState());System.out.println("t2 state:" + t2.getState());System.out.println("t3 state:" + t3.getState());System.out.println("t3 state:" + t3.getState());}public void threadTimeWaitingTest() throws InterruptedException {Thread t1 = new Thread(()->{try {System.out.println("t1 sleep 1000 start");Thread.sleep(1000);System.out.println("t1 sleep 1000 end");} catch (InterruptedException e) {throw new RuntimeException(e);}});t1.start();t1.join();System.out.println("t1 state:" +t1.getState());}public void joinTest() {Thread t3 = new Thread(()->{try {System.out.println("t3 start...");Thread.sleep(1000);System.out.println("t3 end.");} catch (InterruptedException e) {throw new RuntimeException(e);}});Thread t2 = new Thread(()->{try {System.out.println("t2 start...");t3.join();System.out.println("t2 end.");} catch (InterruptedException e) {throw new RuntimeException(e);}});Thread t1 = new Thread(()->{try {System.out.println("t1 start...");t2.join();System.out.println("t1 end.");} catch (InterruptedException e) {throw new RuntimeException(e);}});t1.start();t2.start();t3.start();}public static void main(String[] args) throws InterruptedException {ThreadTest threadTest = new ThreadTest();
//        threadTest.test1();//        threadTest.threadBlockTest();threadTest.threadWaitingTest();//        threadTest.threadTimeWaitingTest();//        threadTest.joinTest();}
}

二、线程间执行结果接收处理

java">package org.example;import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;public class MyCallbale implements Callable<Integer> {@Overridepublic Integer call() throws Exception {int sum = 0;for (int i = 0; i < 10; i++) {sum += i;}return sum;}
}class FutureTeskExample {public static void main(String[] args) throws ExecutionException, InterruptedException {MyCallbale myCallbale = new MyCallbale();FutureTask<Integer> integerFutureTask = new FutureTask<>(myCallbale);Thread thread = new Thread(integerFutureTask);thread.start();Integer i = integerFutureTask.get();System.out.println("Result :" + i);}
}

三、线程池

java">package org.example;import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;public class ExecutorServiceExample {public void multipleCallableExample() throws InterruptedException, ExecutionException {ExecutorService executorService = Executors.newFixedThreadPool(3);List<Callable<Integer>> callables = new ArrayList<>();callables.add(()->1);callables.add(()->2);callables.add(()->3);List<Future<Integer>> futures = executorService.invokeAll(callables);for (Future<Integer> future : futures) {Integer i = future.get();System.out.println(i);}}public void singalThreadPool () throws ExecutionException, InterruptedException {ExecutorService executorService = Executors.newFixedThreadPool(1);MyCallbale myCallbale = new MyCallbale();Future<Integer> future = executorService.submit(myCallbale);Integer i = future.get();System.out.println("result :" + i);}public static void main(String[] args) throws ExecutionException, InterruptedException {ExecutorServiceExample executorServiceExample = new ExecutorServiceExample();executorServiceExample.singalThreadPool();ExecutorServiceExample executorServiceExample1 = new ExecutorServiceExample();executorServiceExample1.multipleCallableExample();}
}


http://www.ppmy.cn/devtools/152010.html

相关文章

SpringBoot+Vue小区智享物业管理系统(高质量源码,可定制,提供文档,免费部署到本地)

作者简介&#xff1a;✌CSDN新星计划导师、Java领域优质创作者、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和学生毕业项目实战,高校老师/讲师/同行前辈交流。✌ 主要内容&#xff1a;&#x1f31f;Java项目、Python项目、前端项目、PHP、ASP.NET、人工智能…

三台 Centos7.9 中 Docker 部署 Redis 哨兵模式

三台 Centos7.9 中 Docker 部署 Redis 哨兵模式 1. 环境规划2. 配置 Docker Compose3. 配置 Redis 密码和持久化4. 配置哨兵5. 启动服务6. 验证 Redis 哨兵模式7. 注意事项 1. 环境规划 三台服务器的角色分配如下&#xff1a; IP Address容器端口角色192.168.15.128redis-mas…

Leetcode - 周赛431

目录 一&#xff0c;3411. 最长乘积等价子数组 二&#xff0c;3412. 计算字符串的镜像分数 三&#xff0c;3413. 收集连续 K 个袋子可以获得的最多硬币数量 四&#xff0c;3414. 不重叠区间的最大得分 一&#xff0c;3411. 最长乘积等价子数组 本题数据范围小&#xff0c;直…

51单片机——DS18B20温度传感器

由于DS18B20数字温度传感器是单总线接口&#xff0c;所以需要使用51单片机的一个IO口模拟单总线时序与DS18B20通信&#xff0c;将检测的环境温度读取出来 1、DS18B20模块电路 传感器接口的单总线管脚接至单片机P3.7IO口上 2、DS18B20介绍 2.1 DS18B20外观实物图 管脚1为GN…

【linux命令】ip命令使用

1、设置网口IP 方法1&#xff1a;通过IP设置网口ip 添加静态IP&#xff1a; ip addr add 1.1.1.1/24 dev eth0 删除ip: ip addr del 1.1.1.1/24 dev eth0 方法2&#xff1a;nmtui 配置IP另外方法&#xff1a; nmtui 2、添加路由 添加路由&#xff1a; ip route add 目标网…

RV1126+FFMPEG推流项目(9)AI和AENC模块绑定,并且开启线程采集

前面两篇已经交代AI和AENC模块的配置&#xff0c;这篇就让这两个模块绑定起来&#xff0c;绑定的原因是&#xff0c;Aenc从Ai模块拿到采集的原始数据进行编码。 使用 RK_MPI_SYS_Bind 把 AI 节点和 AENC 进行绑定&#xff0c;其中 enModId 是模块 ID 号选择的是 RK_ID_AI、s32C…

智能网联汽车的数据脱敏

2021 年施行的数据安全法旨在规范数据处理活动&#xff0c;保障数据安全&#xff0c;促进包括自动驾驶数据在内的开发利用&#xff0c;保护个人、组织的合法权益&#xff0c;维护国家主权、安全和发展利益。同年施行的个人信息保护法则进一步细化了个人信息权益的保护&#xff…

知识图谱实体对齐工具浅析

知识图谱实体对齐工具是用于将不同知识图谱或数据源中的相同实体进行匹配和融合的技术。以下是几种常见的知识图谱实体对齐工具及其方法&#xff1a; 基于嵌入的方法&#xff1a; TransE、TransR、TransD、TransH、TransG&#xff1a;这些方法通过将实体和关系嵌入到低维向量空…