下面是一个自定义的App类和MainActivity类别代码示例代码示例:怎么了之前发生关系建立在这两个线程的Android
public class App extends Application {
private static String TAG = "APP";
private int i;
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, Thread.currentThread().getName());
HandlerThread t = new HandlerThread("init-thread");
t.start();
i = -100;
Handler handler = new Handler(t.getLooper());
handler.post(new Runnable() {
@Override
public void run() {
i = 100;
}
});
handler.post(new Runnable() {
@Override
public void run() {
MainActivity.MainHandler h = new MainActivity.MainHandler(Looper.getMainLooper(), App.this);
h.sendEmptyMessage(0);
}
});
}
public int getI() {
return i;
}
}
而且MainActivity类别:
public class MainActivity extends Activity {
private static String TAG = "ACT-1";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
super.onResume();
App app = (App) getApplication();
Log.e(TAG, "i: " + app.getI()); //prints 100
}
public static class MainHandler extends Handler {
private Application application;
public MainHandler(Looper looper, Application app) {
super(looper);
this.application = app;
}
@Override
public void handleMessage(Message msg) {
App app = (App) application;
Log.e(TAG, "MSG.what: " + msg.what);
Log.e(TAG, "i: " + app.getI()); //prints 100
}
}
}
我想要做的是将INIT-THREAD 中的“i”的值更改为100,并尝试从主线程读取值。
我期待的价值“i”的的onResume和的handleMessage是-100,因为它们是在主线程中执行,但日志打印值实际上100
是在某种程度上,我试图重现每个人在常规的java程序中都会犯的经典错误,但是android似乎明智地避免了它。
所以我有兴趣了解android如何实现两个线程之间的发生关系。
实际上,由于Android的处理程序,实际上有一个发生之前的关系。阅读下面的答案。 – Petrakeas 2015-09-29 14:32:42