这段笔记是参照b站教程BV1Rv411y7MU整理而来的,用于个人备忘以便复习,需要的朋友可以自取。
线程间通讯(下)
1. ThreadLoad的使用
public class Test {
//定义ThreadLocal对象
private static ThreadLocal threadLocal = new ThreadLocal();
//定义线程类
private static class MyThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
//设置线程相关值
threadLocal.set(Thread.currentThread().getName()+" - "+i);
//调用get方法读取相关值
System.out.println(Thread.currentThread().getName()+" value = "+threadLocal.get());
}
}
}
public static void main(String[]args){
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start();
t2.start();
}
}
- 使用ThreadLocal进行多线程下日期格式转换
/**
* 多线程环境中,把字符串转换成日期对象,多个线程使用通过一个SimpleDateFormat对象可能会产生线程安全问题,有异常
* 为每个线程指定自己的SimpleDateFormat对象,使用ThreadLocal
*/
public class Test01{
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
static ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<>();
public static void main(String[]args){
for (int i = 0; i < 100; i++) {
new Thread(new ParseDate(i)).start();
}
}
//定义Runnable接口
static class ParseDate implements Runnable{
private int i =0;
public ParseDate(int i){
this.i=i;
}
@Override
public void run() {
String text = "2021年11月22日 08:28:"+i%60;
//先判断当前线程是否有SimpleDateFormat对象,没有就创建
try {
if(threadLocal.get()==null){
threadLocal.set(new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"));
}
Date date = threadLocal.get().parse(text);
System.out.println("Date: "+date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
- ThreadLocal设置初始值
public class Test02 {
private static final ThreadLocal<Date> threadLocal = new SubThreadLocal();
//定义一个ThreadLocal的子类
static class SubThreadLocal extends ThreadLocal<Date>{
@Override
protected Date initialValue() {
return new Date();//把当前日期设置为初始值
}
}
public static class MyThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
//第一次调用ThreadLocal的get方法会返回null
System.out.println(Thread.currentThread().getName()+" -- value = "+threadLocal.get());
//没有日期就设置日期
if(threadLocal.get()==null){
threadLocal.set(new Date());
}
}
}
}
public static void main(String[]args){
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start();
t2.start();
}
}