SimpleDateFormat非线程安全测试

package gulixueyuan_jdk18;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.junit.Test;

public class TestSimpleDateFormat {
	
	@Test
	public void test1() throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		System.out.println(sdf.parse("20180415"));
	}
	
	
	public static void main(String[] args) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		Callable<Date> task = new Callable<Date>() {
			
			@Override
			public Date call() throws Exception {
				return sdf.parse("20180415");
			}
		};
		
		ExecutorService pool = Executors.newFixedThreadPool(10);
		
		List<Future<Date>> list = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			list.add(pool.submit(task));
		}
		
		list.forEach(e -> {
			try {
				System.out.println(e.get());
			} catch (InterruptedException | ExecutionException e1) {
				e1.printStackTrace();
			}
		});
		
	}
}

如何使用jdk1.8保证线程安全:

//		 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
		Callable<LocalDate> task = new Callable<LocalDate>() {

			@Override
			public LocalDate call() throws Exception {
				return LocalDate.parse("20180415", dtf);
			}
		};

		ExecutorService pool = Executors.newFixedThreadPool(10);

		List<Future<LocalDate>> list = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			list.add(pool.submit(task));
		}

		list.forEach(e -> {
			try {
				System.out.println(e.get());
			} catch (InterruptedException | ExecutionException e1) {
				e1.printStackTrace();
			}
		});

		pool.shutdown();



阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页