当前位置:网站首页>scala 并行集合、并行并发、线程安全问题、ThreadLocal
scala 并行集合、并行并发、线程安全问题、ThreadLocal
2022-08-03 08:30:00 【但行益事莫问前程】
1. scala并行集合
Scala提供并行集合,用于多核环境的并行计算,充分使用多核CPU
object T34 {
def main(args: Array[String]): Unit = {
val result = (0 to 20).par.map {
x => Thread.currentThread.getName }
println(result)
}
}
并行:两个或多个事件在同一时刻点发生(多核CPU)并发:两个或多个事件在同一时间段内发生(多线程竞争资源)
2. 线程安全问题
多线程并发修改,对共享内存中共享对象属性进行修改所导致的数据冲突问题
public class T45 {
public static void main(String[] args) {
User user = new User();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
user.name = "zs";
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(user.name);
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
user.name = "lisi";
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(user.name);
}
});
thread1.start();
thread2.start();
System.out.println("main");
}
}
class User {
public String name;
}

3. ThreadLocal
ThreadLocal中填充的变量属于当前线程,对其他线程而言是隔离的。ThreadLocal为变量在每个线程中都创建了一个副本,每个线程访问自己内部的副本变量。因此不存在线程安全问题
public class T45 {
public static void main(String[] args) {
User user = new User();
//线程安全问题: 多线程并发修改,对共享内存中共享对象属性进行修改所导致的数据冲突问题
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
user.name.set("zs");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(user.name.get());
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
user.name.set("lisi");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(user.name.get());
}
});
thread1.start();
thread2.start();
System.out.println("main");
}
}
class User {
public ThreadLocal<String> name=new ThreadLocal<>();
}

边栏推荐
- 箭头函数与普通函数的区别
- 二进制日志过期时间设置expire_logs_days
- 2022下半年软考「高项&集成」复习计划ta来喽~
- Qt 下拉复选框(MultiSelectComboBox)(一) 实现下拉框多选,搜索下拉框内容
- rust 学习笔记
- Arduino框架下对ESP32 NVS非易失性存储解读以及应用示例
- ArcEngine (six) use the tool tool to realize the zoom in, zoom out and translation of the pull box
- 36氪详情页AES
- 数仓4.0(二)------ 业务数据采集平台
- gpnmb+ gpnmb-AT2 cell空转映射 上皮细胞的空转映射
猜你喜欢
随机推荐
线性表
window的供选数据流
流行和声基础大笔记
开发工具之版本控制
WPS EXCEL 筛选指定长度的文本 内容 字符串
MySQL2
ArcEngine (3) zoom in and zoom out through the MapControl control to achieve full-image roaming
Logic Pro X自带音色库列表
数仓4.0(二)------ 业务数据采集平台
如何在安装GBase 8c数据库的时候,报错显示“Host ips belong to different cluster?
dflow部署简记
2022下半年软考「高项&集成」复习计划ta来喽~
ArcEngine(八)用IWorkspaceFactory加载矢量数据
二进制日志过期时间设置expire_logs_days
ceph简介
集群
frp: open source intranet penetration tool
安装mysql-workbench
Docker启动mysql
002-字段不为null









