当前位置:网站首页>Scala parallel collections, parallel concurrency, thread safety issues, ThreadLocal
Scala parallel collections, parallel concurrency, thread safety issues, ThreadLocal
2022-08-03 08:32:00 【But do good things, don't ask about the future】
1. scala并行集合
ScalaProvide parallel collection,用于多核环境的并行计算,充分使用多核CPU
object T34 {
def main(args: Array[String]): Unit = {
val result = (0 to 20).par.map {
x => Thread.currentThread.getName }
println(result)
}
}
并行
:Two or more events occur at the same time
(多核CPU)并发
:两个或多个事件在同一时间段内发生
(Multithreaded competition resources)
2. 线程安全问题
Multi-threaded concurrent modification,To modify a Shared object attribute in the Shared memory
所导致的数据冲突问题
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中填充的变量属于当前线程,For other threads is to isolate the.ThreadLocal为变量在每个线程中都创建了一个副本
,Copies of each thread access to their internal variables.因此不存在线程安全问题
public class T45 {
public static void main(String[] args) {
User user = new User();
//线程安全问题: Multi-threaded concurrent modification,Shared in the Shared memory object properties caused by modified data conflict
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<>();
}
边栏推荐
猜你喜欢
随机推荐
使用pipreqs导出项目所需的requirements.txt(而非整个环境)
Using pipreqs export requirements needed for the project. TXT (rather than the whole environment)
Charles packet capture tool learning record
HCIP练习02(OSPF)
行业洞察 | 如何更好的实现与虚拟人的互动体验?
Redis的基础与django使用redis
IDEA的database使用教程(使用mysql数据库)
【微信小程序】底部有安全距离,适配iphone X等机型的解决方案
dflow入门1——HelloWorld!
【论文笔记】基于动作空间划分的MAXQ自动分层方法
获取JDcookie的方法
基于二次型性能指标的燃料电池过氧比RBF-PID控制
ArcEngine (1) Loading vector data
swiper分类菜单双层效果demo(整理)
mysql5.7服务器The innodb_system data file 'ibdata1' must be writable导致无法启动服务器
手把手教你如何自制目标检测框架(从理论到实现)
dflow入门3——dpdispatcher插件
编程踩坑合集
netstat 及 ifconfig 是如何工作的。
FusionAccess软件架构、FusionAccess必须配置的四个组件、桌面发放流程、虚拟机组类型、桌面组类型