/*
* 匿名Thread几种方法:
* 1) 重写run方法:通过new Thread(){}.start() 直接new一个实例后实现并start, 实现里面重写run方法
* 2) 调用runable接口:new Thread( new Runable(){} ).start()
* 3) 通过lambda传参给Thread: new Thread( () -> {}).start()
*
* Task:
* “yyyy-MM-dd HH:mm:ss”的格式打印当前系统时间,总循环10次,每1s调用一次
* */
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.SimpleTimeZone;
public class useLib {
// 1 通过lambda,最简洁
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yy-MM-dd HH:mm:ss");
new Thread(()->{
for(int i = 0; i < 10; i++) {
System.out.println("<M1" + dtf.format(LocalDateTime.now()));
try{
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
).start();
// 2 通过run方法,最直接
System.out.println("Method 2: by run method");
SimpleDateFormat d = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
new Thread() {
@Override
public void run() {
for (int i = 0; i < 10; i ++) {
String str = d.format(new Date());
System.out.println(">M2" + str);
try{
Thread.sleep(100);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
//3 通过runable接口,内部仍然需要覆盖run方法
System.out.println("Method3: by runable interface");
DateTimeFormatter dt = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
new print().print(dt.format(LocalDateTime.now()));
new Thread(
new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
new print().print("[M3 " + dt.format(LocalDateTime.now()));
try{
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
).start();
}
}
class print{
public void print(String str) {
System.out.println(str);
}
}
results:
Method 2: by run method
<M121-01-05 15:30:45
Method3: by runable interface
M221-01-05 15:30:45
2021-01-05T15:30:45.9785493
[M3 2021-01-05T15:30:45.9795468
<M121-01-05 15:30:46
M221-01-05 15:30:46
[M3 2021-01-05T15:30:46.0872608
<M121-01-05 15:30:46
M221-01-05 15:30:46
[M3 2021-01-05T15:30:46.1922955
<M121-01-05 15:30:46
M221-01-05 15:30:46
[M3 2021-01-05T15:30:46.297524
<M121-01-05 15:30:46
M221-01-05 15:30:46
[M3 2021-01-05T15:30:46.4022459
<M121-01-05 15:30:46
M221-01-05 15:30:46
[M3 2021-01-05T15:30:46.506966
<M121-01-05 15:30:46
M221-01-05 15:30:46
[M3 2021-01-05T15:30:46.611687
<M121-01-05 15:30:46
M221-01-05 15:30:46
[M3 2021-01-05T15:30:46.7164079
<M121-01-05 15:30:46
M221-01-05 15:30:46
[M3 2021-01-05T15:30:46.8211614
<M121-01-05 15:30:46
M221-01-05 15:30:46
[M3 2021-01-05T15:30:46.9258799
Process finished with exit code 0

本文介绍了Java中创建线程的三种常见方法:使用Lambda表达式、重写Thread类的run方法及实现Runnable接口,并展示了如何利用这些方法以特定格式输出当前系统时间。
525

被折叠的 条评论
为什么被折叠?



