异步API
对于多任务耗时的业务场景java日期格式化,一般我们会用到线程异步处理,在以前我们用 Thread 或者 Runnable 来实现异步,这是oracle官方做法,不过缺点很明显
现在,java8为我们提供了CompletableFuture类,可以完全解决以上问题。
主要方法有:
@Test
public void asyncThread()throws Exception{
CompletableFuture async1 = CompletableFuture.runAsync(()->{
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName());
System.out.println("none return Async");
}catch (Exception e){
e.printStackTrace();
}
});
// 调用get()将等待异步逻辑处理完成
async1.get();
}
@Test
public void asyncThread2()throws Exception{
CompletableFuture async2 = CompletableFuture.supplyAsync(()->{
return "hello";
});
String result = async2.get();
// String result2 = async2.get(5L, TimeUnit.SECONDS);
System.out.println(result);
}
@Test
public void asyncThread3()throws Exception{
CompletableFuture a = CompletableFuture.supplyAsync(() -> "hello");
CompletableFuture b = CompletableFuture.supplyAsync(() -> "youth");
CompletableFuture c = CompletableFuture.supplyAsync(() -> "!");
CompletableFuture all = CompletableFuture.allOf(a,b,c);
all.get();
String result = Stream.of(a, b,c)
.map(CompletableFuture::join)
.collect(Collectors.joining(" "));
System.out.println(result);
}
@Test
public void asyncThread4()throws Exception{
CompletableFuture a = CompletableFuture.supplyAsync(() ->{
try{
Thread.sleep(20);
return "hello";
}catch (Exception e){
e.printStackTrace();
return "none~";
}
});
CompletableFuture b = CompletableFuture.supplyAsync(() -> "youth");
CompletableFuture c = CompletableFuture.supplyAsync(() -> "!");
CompletableFuture
循环ForEach
java8 在原有for或iterator循环下又提供了 forEach 的方法,不过与for循环不同的是 forEach 循环是建立在stream之上的,而且比for或iterator方便的是,他可以循环Map对象, 如果您尝试配合filter处理就更赞了~
@Test
public void listForeach(){
List lst = new ArrayList(5){{
add("A");
add("B");
add("H");
add("O");
add("M");
}};
lst.forEach(System.out::println);
lst.forEach((item)-> System.out.println(item.concat("_")));
}
@Test
public void arrForeach(){
String[] strArr = new String[]{"A","B","C","D"};
Arrays.stream(strArr).forEach(System.out::println);
}
@Test
public void numericForeach(){
IntStream.range(0,10).forEach(System.out::println);
}
@Test
public void mapForeach(){
Map mps = new HashMap(5){{
put("a",1);
put("b",true);
put("c",23.44F);
put("d","hello");
put("e",11L);
}};
mps.forEach((k,v)-> System.out.println(k.concat(":").concat(String.valueOf(v))));
String str = "hello";
}
新的时间类(LocalDate、LocalDateTime)
java8 之前我们处理时间 大多会涉及到这几个类Date、SimpleDateFormat、Calendar ,这种处理方式复杂、存在线程隐患、国际化困难、日期加减等处理麻烦等等。
现在有了 LocalDate、LocalDateTime、DateTimeFormatter 生活就变得简单了~详情可以关注公众号Java技术栈搜索阅读这系列的教程。
/**设置格式化模板**/
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSS");
/**设置日期时区常量**/
public static final ZoneId CHINA_ZONE_ID = ZoneId.systemDefault();
/**Date格式化为DateTime**/
@Test
public void dateToDateTime(){
Date date = new Date();
LocalDateTime dateTime = date.toInstant().atZone(CHINA_ZONE_ID).toLocalDateTime();
System.out.println(dateTime);
}
/**LocalDate/LocalDateTime转Date**/
@Test
public void toDate(){
// LocalDate
LocalDate localDate = LocalDate.now();
Date d1 = Date.from(localDate.atStartOfDay(CHINA_ZONE_ID).toInstant());
System.out.println(d1);
// LocalDateTime
LocalDateTime localDateTime = LocalDateTime.now();
Date d2 = Date.from(localDateTime.atZone(CHINA_ZONE_ID).toInstant());
System.out.println(d2);
}
/**日期格式化**/
@Test
public void formatDate(){
System.out.println(LocalDateTime.now().format(DATE_TIME_FORMATTER));
}
/**日期加减**/
@Test
public void plusDay(){
LocalDateTime dateTime = LocalDateTime.now(CHINA_ZONE_ID);
//天
dateTime=dateTime.plusDays(1);
//时
dateTime=dateTime.plusHours(-1);
//分钟
dateTime=dateTime.plusMinutes(30);
System.out.println(dateTime.format(DATE_TIME_FORMATTER));
}
/**日期时间间隔**/
@Test
public void betweenDay(){
// LocalDateTime
LocalDateTime startDate = LocalDateTime.of(2019,07,01,12,12,22);
LocalDateTime endDate = LocalDateTime.of(2019,07,03,12,12,22);
Long withSecond = endDate.atZone(CHINA_ZONE_ID).toEpochSecond() - startDate.atZone(CHINA_ZONE_ID).toEpochSecond();
System.out.println(withSecond/60/60/24);
// LocalDate
LocalDate startDate2 = LocalDate.of(2019,07,01);
LocalDate endDate2 = LocalDate.of(2019,07,03);
Long withSecond2 = endDate2.toEpochDay() - startDate2.toEpochDay();
System.out.println(withSecond2);
}
/**第一天and最后一天**/
@Test
public void theLastDay(){
// 当月第一天
LocalDateTime dateTime = LocalDateTime.of(2019,07,03,12,12,22);
dateTime = dateTime.with(TemporalAdjusters.firstDayOfMonth());
System.out.println(dateTime);
// 当月最后一天
dateTime = dateTime.with(TemporalAdjusters.lastDayOfMonth());
System.out.println(dateTime);
//当月的第几天
dateTime = LocalDateTime.now();
int dayOfMonth = dateTime.getDayOfMonth();
System.out.println(dayOfMonth);
// 当前周的第几天
int dayOfWeek = dateTime.getDayOfWeek().getValue();
System.out.println(dayOfWeek);
}
OKjava日期格式化,本次分享就到这里,如有谬误恳请指正~
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。