0

I want to run two Threads in parallel twice in a row with different priorities to see the difference.

Therefore I call this Method twice.

    private static void work() {
        thread1.start();
        thread2.start();

        for (int counter = 0; counter < 50; counter++) {
            System.out.println(i.get());
            try{
                Thread.sleep(200);
            }catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        thread1.stopRunning();
        thread2.stopRunning();

        System.out.println("Run beendet");
    }

The Threads look like this:

public class IncrementLoopThread extends Thread {
    AtomicInteger i;
    private boolean running;

    public IncrementLoopThread(AtomicInteger i) {
        this.i = i;
    }

    @Override
    public void run() {
        running = true;
        while (running) {
            i.incrementAndGet();
        }
    }

    public void stopRunning() {
        running = false;
    }
}

I get an IllegalThreadStateException

Surfdrum
  • 1
  • 1
  • 6
    You cannot start threads more than once. End of story. Don't extend thread, implement runnable, then call. `new Thread( myRunnable ).start()` – matt Dec 22 '21 at 09:49

0 Answers0