【Java】同步与异步Timer Friday, August 18, 2023 本文共219字 1分钟阅读时长 posts 杂谈 订阅 ⚠️本文是作者P3troL1er原创,首发于https://peterliuzhi.top/posts/java%E5%90%8C%E6%AD%A5%E4%B8%8E%E5%BC%82%E6%AD%A5timer/。商业转载请联系作者获得授权,非商业转载请注明出处! Autumn is a second spring when every leaf is a flower. — Albert Camus 引入 需求: 纯粹的计时功能 计时结束时调用回调函数 基于多线程实现异步 代码 首先定义Timer类 public class Timer { public void alarm(long millis, Callable callable) { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(millis); } catch (Exception e) { e.printStackTrace(); } callable.call(); } }).start(); } public void wait(long millis, Callable callable) { try { Thread.sleep(millis); } catch (Exception e) { e.printStackTrace(); } callable.call(); } } 然后定义回调函数的类型,通过接口实现 package hundsun.email.Entity; public interface Callable { /** * 回调函数 */ public void call(); } 如果你要使用这个Timer,首先需要实现Callable接口 public class TestClass implements Callable { static int a = 0; @Override public void call() { a++; System.out.println("Timer alarmed!" + a); } public static void main(String[] args) { Timer timer = new Timer(); timer.alarm(3000, new TestClass()); System.out.println("-----------"); timer.wait(3000, new TestClass()); } } 点此订阅P3troL1er的博客! 点此复制分享二维码! 点此复制分享信息! 扫码阅读此文章 点击按钮复制分享信息 点击订阅