高分悬赏:Java语言多线程倒计时怎么同步输出,怎么用多线程来实现
高分悬赏:Java语言多线程倒计时怎么同步输出,怎么用多线程来实现
JUC 提供了很多同步工具,倒计时可以用 CountDownLatch 锁来实现,可以参考我的一篇文章:https://blog.csdn.net/wojiushiwo945you/article/details/103689220
题目不清楚,是多个线程同时打印倒计时,还是各个线程自己打印自己的倒计时?关键就是同步而已
import java.util.Date;
public class Sample {
public static void main(String[] args) {
Runnable r = new Runnable() { //多线程同时打印一个倒计时
int seconds = 30; //倒计30秒
public void run() {
int current = seconds;
while (current > 0) {
try {
synchronized(this) {
if (current == seconds) {
Date d = new Date();
System.out.printf("%s:倒数%d秒, time:%tT\n",
Thread.currentThread().getName(), current, d);
seconds--;
}
current = seconds;
}
Thread.sleep(1000);
synchronized(this) {
if (current == 0) {
System.out.printf("%s:倒计时结束。\n", Thread.currentThread().getName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
for (int i=0; i<10; i++) { //多线程同时打印一个倒计时
new Thread(r).start();
}
/* 多线程各自打印自己的倒计时
Object locker = new Object();
for (int i=0; i<10; i++) {
new Thread() {
int seconds = 30;
public void run() {
while (seconds > 0) {
try {
synchronized(locker) {
Date d = new Date();
System.out.printf("%s:倒数%d秒, time:%tT\n",
Thread.currentThread().getName(), seconds--, d);
}
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.printf("%s:倒计时结束。\n", Thread.currentThread().getName());
}
}.start();
}
*/
}
}
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();
}
}
}