创建线程后创建对象(下面的方法 A)与在当前线程中创建对象并将其传递给新线程(方法 B)之间有什么区别吗?
方法一:
public class AppA {
private A app;
public void run() {
Runnable runnable = () -> {
this.app = new A();
};
Thread workerA = new Thread(runnable);
workerA.start();
}
}
public class A {
private final EventDispatcher dispatcher;
A() {
this.dispatcher = new EventDispatcher();
}
}
public static void main(String[] args) {
AppA appA = new AppA();
appA.run();
}
方法B:
public class AppB {
private B app;
public void run() {
EventDispatcher dispatcher = new EventDispatcher();
Runnable runnable = () -> {
this.app = new B(dispatcher);
};
Thread workerB = new Thread(runnable);
workerB.start();
}
}
public class B {
private final EventDispatcher dispatcher;
B(EventDispatcher dispatcher) {
if (dispatcher == null) {
throw new NullPointerException();
}
this.dispatcher = dispatcher;
}
}
public static void main(String[] args) {
AppB appB = new AppB();
appB.run();
}
App 在单线程中创建的对象。
app.run() 从单线程调用。
鸿蒙传说
忽然笑
慕码人2483693
相关分类