java的回调和事件驱动

玩聚 2025-7-10 21 7/10

回调函数做异步

// 回调接口:用于通知任务完成
interface DownloadCallback {
    void onComplete(String result);
}

// 模拟的下载器:异步执行下载任务
class Downloader {
    public void downloadFileAsync(String url, DownloadCallback callback) {
        System.out.println("开始下载:" + url);

        // 创建一个新线程,模拟异步下载
        new Thread(() -> {
            try {
                Thread.sleep(2000); // 模拟耗时操作
                String result = "文件内容:Hello, from " + url;
                // 下载完成,执行回调
                callback.onComplete(result);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

// 主类:演示非阻塞回调
public class NonBlockingCallbackDemo {
    public static void main(String[] args) {
        Downloader downloader = new Downloader();

        // 发起异步下载(不阻塞主线程)
        downloader.downloadFileAsync("http://example.com/file.txt", new DownloadCallback() {
            @Override
            public void onComplete(String result) {
                System.out.println("✅ 回调收到结果:" + result);
            }
        });

        // 主线程继续执行自己的事情
        System.out.println("主线程继续执行其他逻辑,不被阻塞");
    }
}

事件驱动

// 定义按钮事件类型
enum ButtonEventType {
    PRESS,
    RELEASE
}

// 按钮事件类(封装事件信息)
class ButtonEvent {
    private final ButtonEventType type;
    private final long timestamp;

    public ButtonEvent(ButtonEventType type) {
        this.type = type;
        this.timestamp = System.currentTimeMillis();
    }

    public ButtonEventType getType() {
        return type;
    }

    public long getTimestamp() {
        return timestamp;
    }
}

// 按钮监听器接口
interface ButtonListener {
    void onButtonEvent(ButtonEvent event);
}

// 按钮类(事件源)
class Button {
    private java.util.List<ButtonListener> listeners = new java.util.ArrayList<>();

    // 注册监听器
    public void addListener(ButtonListener listener) {
        listeners.add(listener);
    }

    // 模拟按钮按下
    public void press() {
        System.out.println("🔘 [Button] 被按下");
        fireEvent(new ButtonEvent(ButtonEventType.PRESS));
    }

    // 模拟按钮弹起
    public void release() {
        System.out.println("🔘 [Button] 被弹起");
        fireEvent(new ButtonEvent(ButtonEventType.RELEASE));
    }

    // 通知所有监听器
    private void fireEvent(ButtonEvent event) {
        for (ButtonListener listener : listeners) {
            listener.onButtonEvent(event);
        }
    }
}

// 主类:测试按钮事件机制
public class ButtonEventDemo {
    public static void main(String[] args) throws InterruptedException {
        Button button = new Button();

        // 注册按钮监听器
        button.addListener(new ButtonListener() {
            @Override
            public void onButtonEvent(ButtonEvent event) {
                if (event.getType() == ButtonEventType.PRESS) {
                    System.out.println("✅ [监听器] 检测到按钮按下,时间:" + event.getTimestamp());
                } else if (event.getType() == ButtonEventType.RELEASE) {
                    System.out.println("✅ [监听器] 检测到按钮弹起,时间:" + event.getTimestamp());
                }
            }
        });

        // 模拟用户操作
        System.out.println("用户开始操作按钮...\n");

        button.press();
        Thread.sleep(1000);  // 模拟按住 1 秒
        button.release();
    }
}

 

- THE END -

玩聚

7月10日17:05

最后修改:2025年7月10日
0

非特殊说明,文章内容整理自互联网。

共有 0 条评论