JAVA 回调实例

自己写了一个例子演示JAVA中对耗时操作的回调通知,要求客户程序员实现抽象类Test中的回调接口onCompletion(),代码如下:

interface RequestListener{
	public void request(String action);
	public void onCompletion(String response);
}

abstract class Test implements RequestListener{
	@Override
	public void request(final String action) {
		System.out.println("received request-->"+action);
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Thread.sleep(10000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				onCompletion("requested work done=" + action);
			}
		}).start();
		System.out.println("request return...");
	}
	
}

public class AnyTest extends Test{
@Override
	public void onCompletion(String response) {
		System.out.println(response);
	}

	public void ownWork(){
		System.out.println("My own work...");
	}

	public static void main(String[] args){
		AnyTest at = new AnyTest();
		at.request("WORK1");
		at.ownWork();
	}
}

输出:

received request-->WORK1
request return...
My own work...
requested work done=WORK1

JAVA 回调实例,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。