一個簡單的回調實現

@FunctionalInterface
public interface CallBack {
	public void report(int num);
}

public class Boss implements CallBack {

	public void order(Employee e) {
		System.out.println("boss 下達任務,等待員工去完成。。。");
		Thread t = new Thread() {
			public void run() {
				e.complete((i) -> {
					report(i);
				});
			}
		};
		t.start();
		bossDoOtherWork();
	}

	private void bossDoOtherWork() {
		System.out.println("boss do other work");
	}

	@Override
	public void report(int num) {
		System.out.println("員工報告回饋信息" + num);
	}

	public static void main(String[] args) {
		new Boss().order(new Employee());
	}

}

public class Employee {

	public void complete(CallBack callback) {
		System.out.println("Work begin。。。");
		try {
			
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("I have completed the work");
		callback.report(3);
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章