线程不安全类与写法
程序员文章站
2024-03-26 09:36:17
...
>>>>>>>>>>>>>>>>>>>>>点击领取阿里云优惠券<<<<<<<<<<<<<<<<<<<<<
StringBuffer 与 StringBuilder
代码示例 1
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
*
* StringBuilder 线程不安全, 在一个方法内部定义局部变量进行使用的时候,
* 属于堆栈封闭, 这个时候只有单个线程才能操作这个对象,这个时候就不涉及线程安全的问题.
* eg. 在方法内部定义一个StringBuilder 对象来操作 字符串
*/
@Slf4j
public class StringExample1 {
// 请求总数
public static int clientTotal = 5000;
// 同时并发执行的线程数
public static int threadTotal = 200;
public static StringBuilder stringBuilder = new StringBuilder();
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool(); // 线程池
final Semaphore semaphore = new Semaphore(threadTotal); //信号量
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal); // 计数器闭锁
for (int i = 0;i<clientTotal;i++) {
executorService.execute(() ->{
try {
semaphore.acquire();
update();
semaphore.release();
} catch (Exception e) {
log.error("exception ", e);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
log.info("size:{}", stringBuilder.length());
}
private static void update(){
stringBuilder.append("1");
}
}
运行结果是小于 5000 的
13:49:53.168 [main] INFO com.mmall.concurrency.example.commonUnsafe.StringExample1 - size:4994
代码示例 2
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
*
* StringBuffer 线程安全,其方法有 synchronized 关键字修饰, 每次只能让一个线程来使用, 这样势必就会在性能上有所损失
*/
@Slf4j
public class StringExample2 {
// 请求总数
public static int clientTotal = 5000;
// 同时并发执行的线程数
public static int threadTotal = 200;
public static StringBuffer stringBuffer= new StringBuffer();
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool(); // 线程池
final Semaphore semaphore = new Semaphore(threadTotal); //信号量
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal); // 计数器闭锁
for (int i = 0;i<clientTotal;i++) {
executorService.execute(() ->{
try {
semaphore.acquire();
update();
semaphore.release();
} catch (Exception e) {
log.error("exception ", e);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
log.info("size:{}", stringBuffer.length());
}
private static void update(){
stringBuffer.append("1");
}
}
SimpleDateFormat 与 JodaTime
代码示例 3
import lombok.extern.slf4j.Slf4j;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* SimpleDateFormat 不是一个线程安全的对象
*/
@Slf4j
public class DateFormatExample1 {
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
// 请求总数
public static int clientTotal = 5000;
// 同时并发执行的线程数
public static int threadTotal = 200;
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool(); // 线程池
final Semaphore semaphore = new Semaphore(threadTotal); //信号量
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal); // 计数器闭锁
for (int i = 0;i<clientTotal;i++) {
executorService.execute(() ->{
try {
semaphore.acquire();
add();
semaphore.release();
} catch (Exception e) {
log.error("exception ", e);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
}
private static void add(){
try {
simpleDateFormat.parse("20180405");
} catch (ParseException e) {
log.error("parse Exception", e);
}
}
}
运行结果 , 可以看到, 当多线程并发执行的时候, 出现了很多的异常 , 所以 要使用SimpleDateFormat
必须声明它为局部变量才可以.
线程安全的 日期转换类 JodaTime
, 它不是Java提供的 . 可以通过maven依赖加入
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.8.2</version>
</dependency>
代码示例 4
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* Created by Charles Date:2018/3/22
*/
@Slf4j
public class DateFormatExample3 {
// 请求总数
public static int clientTotal = 5000;
// 同时并发执行的线程数
public static int threadTotal = 200;
private static DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyyMMdd");
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool(); // 线程池
final Semaphore semaphore = new Semaphore(threadTotal); //信号量
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal); // 计数器闭锁
for (int i = 0;i<clientTotal;i++) {
executorService.execute(() ->{
try {
semaphore.acquire();
add();
semaphore.release();
} catch (Exception e) {
log.error("exception ", e);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
}
private static void add(){
DateTime.parse("20180322", dateTimeFormatter).toDateTime();
log.info("ee,{}",DateTime.parse("20180322", dateTimeFormatter).toDateTime());
}
}