Java多線程倒計時同時輸出
如下代碼,簡潔實現count個線程,同步打印倒計時:
public class ThreadSync {
public static void main(String[] args) {
// 開啓5個線程,同步輸出倒計時30s,
threadMethod(5, 30);
}
// count 線程數量,seconds倒計時秒數
public static void threadMethod(int count, int seconds) {
// 格式化時間輸出
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 遍歷線程
for (int i = 0; i < count; i++) {
// lambda 表達式實現函數式接口
new Thread(() -> {
// 線程本地變量,線程安全
ThreadLocal<Integer> local = new ThreadLocal<>();
local.set(seconds);
while (true) {
System.out.println(String.format("線程:%s,倒計時:%d,當前時間:%s", Thread.currentThread().getId(),
local.get(), sf.format(new Date())));
if (local.get() == 0)
break;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
local.set(local.get() - 1);
}
}).start();
}
}
}
結果如圖: