当前位置:网站首页>IDEA05:线程管理
IDEA05:线程管理
2022-08-09 05:05:00 【Jeremy_权】
写在前面
这里主要介绍一下如何使用Java多线程以及实现线程互斥。
一、线程的两种实现方式
- 继承
Thread基类
public class Thread_Test extends Thread{
@Override
public void run() {
System.out.println("Thread is running.");
}
public static void main(String[] args) {
Thread_Test t = new Thread_Test();
// 启动线程,调用run方法
t.start();
}
}
- 实现
Running接口(推荐使用)
public class Thread_Test implements Runnable{
@Override
public void run() {
System.out.println("Thread is running.");
}
public static void main(String[] args) {
Thread_Test t = new Thread_Test();
// 启动线程,调用run方法
Thread thread = new Thread(t);
thread.start();
}
}
二、线程池
- 使用线程池之后可以控制最大能够创建的线程,避免资源浪费;
- 如果要使用线程池的话,线程类只能是通过实现
Running接口来实现; - 如果线程池耗尽,则后续的线程任务会等待有空闲的线程才会创建执行。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Thread_Test implements Runnable {
@Override
public void run() {
System.out.println("Thread is running.");
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
// 最大线程数量
int threadNum = 2;
// 建立线程池
ExecutorService threadPool = Executors.newFixedThreadPool(threadNum);
while(true) {
Thread_Test t = new Thread_Test();
// 提交到线程池执行
threadPool.execute(t);
}
}
}
三、线程互斥
- 主要是使用了
synchronized保留字; - 注意互斥锁的使用会相当影响运行效率,仅在必要时候使用;
- 一般有三种用法:
- 使用一个额外的类对象作为互斥锁
- 适用于需要进行多对象之间的线程互斥的情况;
- 额外的对象可以是最简单的类,无需具体实现,如下面的
Semaphore类; - 这种用法最为普适。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class Semaphore {
}
public class Thread_Test implements Runnable {
private Semaphore semaphore;
public Thread_Test(Semaphore s) {
this.semaphore = s;
}
@Override
public void run() {
System.out.println("Thread is running.");
// 进入临界代码区
synchronized (semaphore) {
System.out.println("Enter critical code area.");
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) {
// 最大线程数量
int threadNum = 2;
// 建立线程池
ExecutorService threadPool = Executors.newFixedThreadPool(threadNum);
// 互斥锁
Semaphore s = new Semaphore();
while(true) {
Thread_Test t = new Thread_Test(s);
// 提交到线程池执行
threadPool.execute(t);
}
}
}
- 使用本对象作为互斥锁
- 适用于同一个对象多次创建线程的情况;
- 只要是在同一个类中的函数需要互斥都可以使用;
- 使用
this作为互斥锁。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Thread_Test implements Runnable {
public Thread_Test() {
// 进入临界代码区
synchronized (this) {
System.out.println("Main: Enter critical code area.");
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
@Override
public void run() {
System.out.println("Thread is running.");
// 进入临界代码区
synchronized (this) {
System.out.println("Thread: Enter critical code area.");
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) {
// 最大线程数量
int threadNum = 10;
// 建立线程池
ExecutorService threadPool = Executors.newFixedThreadPool(threadNum);
Thread_Test t = new Thread_Test();
while(true) {
// 提交到线程池执行
threadPool.execute(t);
}
}
}
- 直接使用
synchronized修饰类内函数
- 本质上也是使用了
this作为互斥锁; - 修饰的函数中的所有代码均为临界代码区。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Thread_Test implements Runnable {
public Thread_Test() {
}
public synchronized void read() {
System.out.println("Thread is reading.");
try {
Thread.currentThread().sleep(200);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void write() {
System.out.println("Thread is writing.");
try {
Thread.currentThread().sleep(200);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
System.out.println("Thread is running.");
this.read();
this.write();
}
public static void main(String[] args) {
// 最大线程数量
int threadNum = 5;
// 建立线程池
ExecutorService threadPool = Executors.newFixedThreadPool(threadNum);
Thread_Test t = new Thread_Test();
while(true) {
// 提交到线程池执行
threadPool.execute(t);
}
}
}
边栏推荐
- JS-DOM-对象的事件onload、匿名函数、this
- 【HMS core】【Ads Kit】Huawei Advertising——Overseas applications are tested in China. Official advertisements cannot be displayed
- C进阶-C语言文件操作
- 无法通过头文件中的宏定义或全局变量修改动态库中的参数
- 通讯录(文件版)(C语言)(VS)
- 硅光电池采集用于植物叶片农残检测
- JS-DOM-全局、局部、隐式变量,数组()\函数、 prompt输入对话框、confirm(确定用户的决定-弹出对话框)
- 【开发者必看】【push kit】推送服务服务典型问题合集2
- 不能提取结果集,SQL [n / a]; org.hibernate.exception.SQLGrammarExcept是嵌套的异常
- 【HMS Core】【FAQ】【AR Engine】AR Engine常见问题合集
猜你喜欢

equals和==

C Advanced - Program Compilation (Preprocessing) + Linking
![[Harmony OS] [ArkUI] ets development graphics and animation drawing](/img/36/f4c91f794b1321f11a24505d1617fb.png)
[Harmony OS] [ArkUI] ets development graphics and animation drawing

Address Book (File Version) (C Language) (VS)

通讯录(文件版)(C语言)(VS)

JS-全局dom对象的使用---使用htm样式和js函数动作的完全分离

The development trend of software testing

力扣349-两个数组的交集——HashSet

微服务架构基础 微服务相关概念及基础知识 贺兰的微博

C Advanced-C Language File Operation
随机推荐
matlab simulink 温度控制时延系统 模糊pid和smith控制
存储系统架构演变
【HMS core】【Ads Kit】Huawei Advertising——Overseas applications are tested in China. Official advertisements cannot be displayed
leetcode:402. 移掉 K 位数字
【Harmony OS】【FAQ】鸿蒙问题合集1
UI框架布局
mysql内容不存在的报错
Faced with risk control, what should Amazon do when evaluating self-supporting accounts?
【Harmony OS】【ARK UI】Date Basic Operation
【计算机网络-哈工大】---学习笔记(下)---(二)Web安全威胁、SSL\IPsec、虚拟专用网、防火墙
【暑期每日一题】洛谷 P1200 [USACO1.1]你的飞碟在这儿Your Ride Is Here
C进阶 - 程序的编译(预处理操作) + 链接
22-08-08 西安 尚医通(04)MongoDB命令、MongoTemplate、MongoRepository
【luogu U142356】Suffix of the Brave (SA) (Chairman Tree) (2 points)
Nacos源码安装
A case of missing heritability
浙江DAMA-CDGA/CDGP数据治理认证招生简章
Still don't know what business intelligence (BI) is?After reading this article, you will understand
STM32系列单片机使用心得
Parameters in dynamic libraries cannot be modified through macro definitions or global variables in header files