Home  >  Article  >  Java  >  How to convert local variables in java SimpleDateFormat

How to convert local variables in java SimpleDateFormat

WBOY
WBOYforward
2023-05-25 14:16:20617browse

Explanation

1. When SimpleDateFormat is defined as a local variable, each thread occupies the SimpleDateFormat target exclusively.

2. It is equivalent to changing a multi-thread program into a single-thread program, so there is no thread insecurity problem.

Example

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
public class SimpleDateFormatExample {
    public static void main(String[] args) {
        // 创建线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        // 执行 10 次时间格式化
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            // 线程池执行任务
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    // 创建 SimpleDateFormat 对象
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
                    // 创建时间对象
                    Date date = new Date(finalI * 1000);
                    // 执行时间格式化并打印结果
                    System.out.println(simpleDateFormat.format(date));
                }
            });
        }
        // 任务执行完之后关闭线程池
        threadPool.shutdown();
    }
}

The above is the detailed content of How to convert local variables in java SimpleDateFormat. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete