手抄报 安全手抄报 手抄报内容 手抄报图片 英语手抄报 清明节手抄报 节约用水手抄报

Java异步调方法实例

时间:2024-10-20 14:52:02

1、使用接口回调方式,异步线程获取数据

2、定义接口OnCallbackLintenerpublic interface OnCallbackLintener { void onCallback(String text);}

3、定义线程类MyThread,重写run方法进行好事操作,该类拥有一个OnCallbackLintener 的成员变量,并且镙烨莲峪添加setListener方法class MyThread extends Thread{ private OnCallbackLsintener listener; public void setListener(OnCallbackLsintener listener) { this.listener = listener; } @Override public void run() { try { Thread.sleep(5000); if (null != listener) { listener.onCallback("The Callback is from myThread"); } } catch (InterruptedException e) { e.printStackTrace(); } }}自定义一个线程,重写run方法,在线程运行时睡眠5秒,5秒之后通过接口回调的方法,发送了一个字符串"The Callback is from myThread"到回调方法中

4、添加main方法进行测试class Test { public static void main(String[] args像粜杵泳) { MyThread thread = new MyThread(); thread.setListener(new OnCallbackLsintener() { @Override public void onCallback(String text) { System.out.println(text); } }); thread.start(); }}附上运行截图

Java异步调方法实例
© 手抄报圈