Java回調

回調接口

public interface CSCallBack {
    void process(String status);
}

服務端實現

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Server {
    public void getClientMsg(CSCallBack csCallBack , String msg) {
        log.info("【服務端】接收到客戶端發送的消息爲:{}", msg);

        // 模擬服務端須要對數據處理
        try {
            Thread.sleep(15 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("【服務端】執行完成");
        String status = "200";
        log.info("【服務端】數據處理成功,返回成功狀態:{}", status);
        csCallBack.process(status);
    }
}

客戶端實現

import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Client implements CSCallBack {
    private Server server;

    public Client(Server server) {
        this.server = server;
    }

    public void sendMsg(final String msg) {
        log.info("【客戶端】發送消息:" + msg);
        // 新起線程的做用就是使asynchronizationTest方法得以異步調用
        new Thread(() -> {
            server.getClientMsg(Client.this, msg);
        }).start();
    }
    /**
     * 具體的回調方法
     *
     * @param status
     */
    public void process(String status) {
        log.info("【客戶端】接收到服務端回調狀態爲:{}", status);
    }

    public void asynchronizationTest() {
        log.info("【客戶端】異步代碼被輸出");
    }
}

測試

/**
 * 一、接口做爲方法參數,其實際傳入引用指向的是實現類
 * 二、Client的sendMsg方法中,參數爲final,由於要被內部類一個新的線程能夠使用。這裏就體現了異步。
 * 三、調用server的getClientMsg(),參數傳入了Client自己(對應第一點)。
 */
public class CallBackTest {
    public static void main(String[] args) {
        Server server = new Server();
        Client client = new Client(server);

        client.sendMsg("Server,Hello~,等待返回消息");
        client.asynchronizationTest();
    }
}
相關文章
相關標籤/搜索