50,549
社区成员
发帖
与我相关
我的任务
分享
public class Sample {
public static void main(String[] args) {
try {
CountDownLatch cd = new CountDownLatch(1);
Thread td = new Thread(()-> { //用线程执行循环
try {
while (!Thread.currentThread().isInterrupted()) {
Thread.sleep(1000*20); //模拟循环线程执行20秒
}
System.out.println("while complete!");
} catch (Exception e) {
System.out.println("while break!");
} finally {
cd.countDown();
}
});
long t1 = System.currentTimeMillis();
td.start();
Thread.sleep(10*1000); //模拟过了10秒
System.out.println("stop loop.");
td.interrupt(); //10秒后中断线程
cd.await();
long t2 = System.currentTimeMillis();
System.out.println("time:" + (t2-t1) + "ms"); //确认时间是否是10秒
} catch (Exception e) {
e.printStackTrace();
}
}
}
至于按键触发事件,如果是swing或awt还好,如果是其他的,比较难实现(非要实现,自己谷歌百度怎么用 jni 吧)