0

この質問のコードは明らかに長すぎたので、コピーして貼り付けるだけで、私が抱えている概念的な問題を網羅していると思われる例を書きました。前作まで読んでくださった方、ありがとうございます!

2 つのファイル

一方が他方を呼び出し、ArrayList を渡します。

2 番目のファイルは ArrayList を変更し、最初のファイルが変更されたファイルにアクセスするための getter を提供します。

ゲッターを呼び出す前に、最初のファイルが 2 番目のファイルの処理を待機するようにするにはどうすればよいですか。現時点では、最初のファイルが待機していないため、このコードは NullPointerException を返します。

実行スレッドでの join() が機能していないようですが、wait() を使用する場合、2 番目のファイルから最初のファイルに notify() するにはどうすればよいですか?

コードは次のとおりです。

public class Launcher implements Runnable {

private ArrayList al = new ArrayList();
private ArrayProcessor ap;

public Launcher(ArrayList al){
    this.al = al;
    ArrayProcessor ap = new ArrayProcessor(al);
}
public static void main(String[] args){
    ArrayList anArray = new ArrayList();
    anArray.add(new Integer(1));
    anArray.add(new Integer(13));
    anArray.add(new Integer(19));
    Launcher l = new Launcher(anArray);
    l.liftOff();
}

public void liftOff(){
    Thread t = new Thread(new Launcher(al));
    synchronized(t){
        t.start();
        try {
            t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    this.ap = new ArrayProcessor(al);
    System.out.println("the array: " + ap.getArray());
}
public void run() {
    ap.doProcess(al);
}

}

および呼び出されたファイル:

public class ArrayProcessor extends Thread{

private ArrayList al;

public ArrayProcessor(ArrayList al){
    this.al = al; 
}

public void doProcess(ArrayList myAL){
    this.start();
}

public void run() {
            // this should increment the ArrayList elements by one
    for (int i=0; i<al.size(); i++){
        int num = ((Integer)al.get(i)).intValue();
        al.set(i, new Integer(++num));
    }
}

public ArrayList getArray(){
    return al;
}

}
4

1 に答える 1

0

あるスレッドが別のスレッドの終了を待機するようにするには、 CountDownLatchを使用できます。サンプルには多くのコードがあるため、ここに小さな POC を示します。

  public static void main(String[] args) throws Exception {

    final CountDownLatch latch = new CountDownLatch(1);

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                System.out.println("Thread doing some work...");
                Thread.sleep(10 * 1000);
                System.out.println("Thread done!");
                latch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }).start();


    System.out.println("Main Thread waiting...");
    latch.await();
    System.out.println("Main Thread can continue");
}
于 2012-08-24T06:07:59.653 に答える