おわかりのように、私はマルチスレッドが初めてで、ここで少し立ち往生しています。私のプログラムPchangeThread
では、プログラムの実行中の任意の時点で別のスレッドからオンとオフを切り替えることができるスレッド (以下の例) が必要です。pixelDetectorOn()
スレッドは開始時に一時停止し、が呼び出されたときに再開する必要があります。
ほとんどの場合、2 つのスレッドは、開始/停止フラグを除いてデータを共有する必要はありません。念のため、とにかくメインスレッドへの参照を含めました。
ただし、以下のコードで出力される唯一のメッセージは「ループに入る前」です。これは、何らかの理由でスレッドが wait() から復帰しないことを示しています。これはある種のロックの問題だと推測していますが、正確に何が問題なのかを理解できていません。this.detector
メインスレッドからロックしても同じ結果が得られます。また、wait()
/notify()
パラダイムが本当にスレッドの中断と起動に適しているかどうか疑問に思っています。
public class PchangeThread extends Thread {
Automation _automation;
private volatile boolean threadInterrupted;
PchangeThread(Automation automation)
{
this._automation = automation;
this.threadInterrupted = true;
}
@Override
public void run()
{
while (true) {
synchronized (this) {
System.out.println("before entering loop");
while (threadInterrupted == true) {
try {
wait();
System.out.println("after wait");
} catch (InterruptedException ex) {
System.out.println("thread2: caught interrupt!");
}
}
}
process();
}
}
private void process()
{
System.out.println("thread is running!");
}
public boolean isThreadInterrupted()
{
return threadInterrupted;
}
public synchronized void resumeThread()
{
this.threadInterrupted = false;
notify();
}
}
resumeThread()
次の方法でメインスレッドから呼び出されます。
public synchronized void pixelDetectorOn(Context stateInformation) {
this.detector.resumeThread();
}
detector
のインスタンスへの参照ですPchangeThread
。「検出」スレッドは、プログラムのメイン モジュールで次のようにインスタンス化されます。
detector=new PchangeThread(this);