0

I am trying to write a SlotMachine applet in Java. The code works through the first time, but when I try to hit the start button a second time, the program crashes. I know that it is an issue with the thread breaks and the Thread.start();. I tried to implement a boolean value "isRunning" instead of the breaks, but that did not work. How do I stop a thread and then start it over? Some insight would be very helpful. Thank you!

import java.awt.*;
import java.awt.event.*;
import java.util.Random;

@SuppressWarnings("serial")
public class SlotMachine extends Frame {
private TextField textWindow1, textWindow2, textWindow3, resultWindow;
private int count1 = 0, count2 = 0, count3 = 0, result1, result2, result3;
private Button toggleButton;
public static final int HEIGHT = 150;
public static final int WIDTH = 100;

box1Thread counter1Thread = new box1Thread();
box2Thread counter2Thread = new box2Thread();
box3Thread counter3Thread = new box3Thread();

public static void main(String[] args) {
    SlotMachine counterWindow = new SlotMachine();
    counterWindow.setVisible(true);

}// main

public SlotMachine() {
    setSize(WIDTH, HEIGHT);

    addWindowListener(new WindowDestroyer());
    setTitle("Slot Machine");
    setBackground(Color.orange);

    setLayout(new FlowLayout());

    textWindow1 = new TextField(1);
    add(textWindow1);
    textWindow1.setText("*");

    textWindow2 = new TextField(1);
    add(textWindow2);
    textWindow2.setText("*");

    textWindow3 = new TextField(1);
    add(textWindow3);
    textWindow3.setText("*");

    toggleButton = new Button("Start");
    toggleButton.addActionListener(new ToggleButtonListener());
    add(toggleButton);

    resultWindow = new TextField(10);
    add(resultWindow);
    resultWindow.setText("");       

}

private class box1Thread extends Thread {

    Random generator1 = new Random();

    public void run() {
        while (true) {
            try {
                Thread.sleep(50);
                result1 = ((count1++) % 4);
                textWindow1.setText(Integer.toString(result1));
            } catch (InterruptedException e) {
                // System.err.println("Interrupted.");
                int randomInt1 = generator1.nextInt(75);
                for (int i = 0; i < randomInt1; i++) {
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e1) {
                        System.err.println("Interrupted.");
                    }
                    result1 = (count1++) % 4;
                    textWindow1.setText(Integer.toString(result1));
                }
                break;

            }
        }
    }
}

private class box2Thread extends Thread {

    Random generator2 = new Random();

    public void run() {
        while (true) {
            try {
                Thread.sleep(50);
                result2 = ((count2++) % 4);
                textWindow2.setText(Integer.toString(result2));
            } catch (InterruptedException e) {
                // System.err.println("Interrupted.");
                int randomInt2 = generator2.nextInt(75);
                for (int i = 0; i < randomInt2; i++) {
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e1) {
                        System.err.println("Interrupted.");
                    }
                    result2 = (count2++) % 4;
                    textWindow2.setText(Integer.toString(result2));
                }
                break;
            }
        }
    }
}

private class box3Thread extends Thread {

    Random generator3 = new Random();

    public void run() {
        while (true) {
            try {
                Thread.sleep(50);
                result3 = ((count3++) % 4);
                textWindow3.setText(Integer.toString(result3));
            } catch (InterruptedException e) {
                // System.err.println("Interrupted.");
                int randomInt3 = generator3.nextInt(75);
                for (int i = 0; i < randomInt3; i++) {
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e1) {
                        System.err.println("Interrupted.");
                    }
                    result3 = (count3++) % 4;
                    textWindow3.setText(Integer.toString(result3));
                }
                break;
            }
        }
    }
}

private class ToggleButtonListener implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("Stop")) {

            counter1Thread.interrupt();
            counter2Thread.interrupt();
            counter3Thread.interrupt();
            toggleButton.setLabel("Wait");
            try {
                counter1Thread.join();
                counter2Thread.join();
                counter3Thread.join();
            } catch (InterruptedException e1) {
                System.err.println("Interrupted.");
            }
            if ((result1 == result2) && (result2 == result3)) {
                resultWindow.setText("You Win!");
            } else {
                resultWindow.setText("Sorry, You Lose!");
            }
            toggleButton.setLabel("Start");

        }

        else if (e.getActionCommand().equals("Start")) {

            counter1Thread.start();
            counter2Thread.start();
            counter3Thread.start();

            toggleButton.setLabel("Stop");
            resultWindow.setText("");

        }
    }
}

}

This is the error I receive:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at SlotMachine$ToggleButtonListener.actionPerformed(SlotMachine.java:166)
at java.awt.Button.processActionEvent(Unknown Source)
at java.awt.Button.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
  • Where is setVisible() method? – Achintya Jha Feb 14 '13 at 06:50
  • Please include the full stacktrace. – Stephen C Feb 14 '13 at 06:51
  • Please explain why you keep tagging your questions "applet" when the code is not an applet. – Stephen C Feb 14 '13 at 06:53
  • possible duplicate of [program throws IllegalThreadStateException](http://stackoverflow.com/questions/14797747/program-throws-illegalthreadstateexception) – Stephen C Feb 14 '13 at 06:59
  • Also see this question for how (not to) restart a Thread : http://stackoverflow.com/questions/1881714/how-to-start-stop-restart-a-thread-in-java – Cyrille Ka Feb 14 '13 at 07:03
  • When you reach the actionPerformed of "Start" in second time , your thread is already terimated . You can verify this by adding "System.out.println(counter1Thread.getState());". If you want your thread to be active then dont terminate your thread – Prateek Sharma Feb 14 '13 at 07:11

2 Answers2

2

How do I stop a thread and then start it over?

You can't. When a thread terminates, it cannot be restarted.

You need to create a new thread and start that ... or not let the previous thread stop. For a more complete answer, refer to the linked question ...

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
2

in your Action performed do following.

else if (e.getActionCommand().equals("Start"))
  {
    counter1Thread = new box1Thread();
    counter2Thread = new box2Thread();
    counter3Thread = new box3Thread();
    counter1Thread.start();
    counter2Thread.start();
    counter3Thread.start();

    toggleButton.setLabel("Stop");
    resultWindow.setText("");

  }

Because once thread is stopped you can not stat is again. So you either don't let thread to stop or create new one .

in previous code I'm creating new thread.

Sumit Singh
  • 15,743
  • 6
  • 59
  • 89