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<>();
}