0

なんらかの理由で、for ループの 2 回目の繰り返しの後、2 回目のスレッド 1 の開始時に java.lang.IllegalThreadStateException が発生します。ここの回答に従って、結合を適切に使用していると思いました。多くのスレッドが完了するのを待つにはどうすればよいですか? . 私の質問は、なぜ 2 回目の反復で例外が発生するのかということです。

public void runThreads(){
        int numofTests;
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the number of iterations to be completed:");
        numofTests = Integer.parseInt(in.nextLine());///Gets the number of tests from the user
        Agent agent = new Agent(numofTests);
        Smoker Pat = new Smoker ("paper", "Pam");
        Smoker Tom = new Smoker ("tobacco", "Tom");
        Smoker Matt = new Smoker ("matches", "Matt");
        Thread thread1 = new Thread(Pat);
        Thread thread2 = new Thread(Tom);
        Thread thread3 = new Thread(Matt);
        Thread thread4 = new Thread(agent);

        for (int i = 0; i < numofTests; i++){
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        try {
            thread1.join();
            thread2.join();
            thread3.join();
            thread4.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        }

    }
4

1 に答える 1

8

スレッドを複数回開始することはできません。ランナブルを複数回実行する場合は、新しいスレッドを再作成します。

于 2013-02-24T00:17:26.250 に答える