2018年12月21日 星期五

java 非同步做法

public interface Callback<T, E> {

    // in: 回傳的資料
    public void back(T in);
  
    // 錯誤時要做的事
    // err 錯誤訊息
    public void error(E err);
}
//----------------------------------------

public class Server_1 {

    public Thread asyncGetData(Callback callback) {
        out.println("server start");
        Thread th_1 = new Thread(() -> {
            int time = (int) (Math.random() * 5000);
          
            out.printf("server thread start(%s)\n", time);
            try {
                Thread.sleep(time);
              
                // 回傳資料
                callback.back(time);
                out.printf("server thread end(%s)\n", time);
            } catch (InterruptedException ex) {
                callback.error(ex);
            }
        });
      
        th_1.start();

        return th_1;
    }
}
//----------------------------------------
public class Client_1 {

    // 資料交換用
    int switchData_int;

    public void getData(){
        out.println("client.getData()");
        Server_1 server_1 = new Server_1();
        int gg;
        Thread th_1 = server_1.asyncGetData(new Callback<Integer, Error>() {
            @Override
            public void back(Integer in) {
                out.println("callback.back");

                // 閉包只適用於套嵌的 class
                Client_1.this.switchData_int = in;
            }

            @Override
            public void error(Error err) {

            }
        });
        try {
            th_1.join();
        } catch (InterruptedException ex) {
            out.println(ex);
        }
        out.printf("result(%s)\n------------\n", this.switchData_int);

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Client_1 cl = new Client_1();
        cl.getData();
        cl.getData();
    }

}