稍加修饰 苏生不语 的代码如下:
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.Scanner;
public class TimeLimit{
public static void main(String[] args) {
//线程池
ExecutorService executorService = Executors.newFixedThreadPool(2);
//线程安全的计数器
AtomicInteger count = new AtomicInteger(0);
//子线程一,用来接收用户输入
executorService.execute(()->{
Scanner input = new Scanner(System.in);
System.out.println("15 秒钟之内,请键入一个字符串,超时自动停机:");
String str = input.next();
count.incrementAndGet();
System.out.printf("谢谢,输入:%s 收到。\n", str);
});
//子线程二,用来倒计时
executorService.execute(()->{
int time = 15;
while (time>0 && count.get() == 0){
try {
Thread.sleep(1000);
time--;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (time==0)
System.out.println("超时。");
count.incrementAndGet();
});
//主线程循环判断计数器的值,只要计数器的值没有改变,就一直等待
while (count.get() == 0){};
//用户已经输入或者倒计时结束
executorService.shutdown();
System.out.println("程序运行结束");
System.exit(0);
}
}