java并发---使用Joda-Time完全替代SimpleDateFormat

SimpleDateFormat是个线程不安全的类,可参考:https://blog.csdn.net/paincupid/article/details/77531362

并且Joda-Time无论在安全还是其他方面都完胜SimpleDateFormat,可以全部使用Joda-Time

以下将如何实现Joda-Time

一,配置pom.xml

        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9</version>
        </dependency>

二,使用例子如下:

import concurrency.annotations.Recommend;
import concurrency.annotations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;
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 William on 2018/5/1 0001
 * import org.joda.time.format.DateTimeFormat;
 * 推荐使用这个类
 */
@Slf4j
@ThreadSafe
@Recommend
public class JodaTimeSafe {

    private static DateTimeFormatter dateTimeFormat = DateTimeFormat.forPattern("yyyyMMdd");
    public static int clientTotal = 5000;
    public static int threadTotal = 200;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(threadTotal);
        CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            int finalI = i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();
                        update(finalI);
                        semaphore.release();
                    } catch (Exception e) {
                        log.error("Exception", e);
                    }
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        executorService.shutdown();
    }

    public static void update(int i) {
        log.info("{},{}", i, dateTimeFormat.parseDateTime("20180501").toDate());
    }
}

猜你喜欢

转载自blog.csdn.net/weianluo/article/details/80154400