同步回调:
打印结果:
1
2
3
public interface Result {
void callBack();
}
public static void main(String[] args) throws InterruptedException {
Entity entity = new Entity();
entity.task(() -> System.out.println("2"));
System.out.println("3");
}
public class Entity {
public void task(Result cb){
try {
Thread.sleep(3000);
System.out.println("1");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
cb.callBack();
}
}
异步回调:
打印结果:
1
2
3
和上面唯一的不同点在于
new Thread(()->{
entity.task(() -> System.out.println("3"));
}).start();
public interface Result {
void callBack();
}
public static void main(String[] args) throws InterruptedException {
Entity entity = new Entity();
new Thread(()->{
entity.task(() -> System.out.println("3"));
}).start();
System.out.println("1");
}
public class Entity {
public void task(Result cb){
try {
Thread.sleep(3000);
System.out.println("2");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
cb.callBack();
}
}
标签:异步,同步,Java,void,System,println,new,public,out
From: https://www.cnblogs.com/laremehpe/p/17318048.html