我试图用线程理解这种并发编程,但我似乎没有得到这个 wait() 和 notify()
我怀疑这与我的一个线程永远等待并且已经调用了通知有关。但我不知道如何解决这个问题。我在stackoverflow上阅读了其他帖子,但不能很好地理解它。
这是我的代码,如果有人能指出我正确的方向,那将会很有帮助。
package com.example.thread_android;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Stage", "onCreate");
Runnable AthreadJob = new ARunnable();
Runnable BthreadJob = new BRunnable();
Thread myThreadOne = new Thread(AthreadJob);
Thread myThreadTwo = new Thread(BthreadJob);
myThreadOne.start();
myThreadTwo.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
class ARunnable implements Runnable{
@Override
public void run(){
Log.d("Runnable", "A Inside Run - WAIT");
try{
synchronized(this){wait();}
} catch (InterruptedException e) {}
//Log.d("Runnable", "A Inside Run - CONTINUE");
}
}
class BRunnable implements Runnable{
@Override
public void run(){
Log.d("Runnable", "B Inside Run");
synchronized (this) {notify();}
}
}