Ошибка IllegalThreadStateException - Java
Формулировка задачи:
Суть игры заключается в том, что есть 3 круга красного цвета, случайным образом выбирается один из них и закрашивается в зеленый. В течении определенного промежутка времени (который постепенно будет уменьшаться) необходимо клацнуть на него мышкой, если этого не происходит, выбирается другой случайный круг. Вот, что у меня получилось
При запуске, после нажатия кнопки start выдает следующее:
Exception in thread "JavaFX Application Thread" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:708)
at yourreaction.YourReaction.GameProcess(YourReaction.java:109)
at yourreaction.YourReaction$1.handle(YourReaction.java:74)
at yourreaction.YourReaction$1.handle(YourReaction.java:72)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:748)
Листинг программы
- package yourreaction;
- import javafx.application.Application;
- import javafx.event.*;
- import javafx.geometry.Pos;
- import javafx.scene.Scene;
- import javafx.scene.control.*;
- import javafx.scene.layout.*;
- import javafx.scene.input.*;
- import javafx.stage.Stage;
- import javafx.scene.shape.Circle;
- import javafx.scene.paint.Color;
- import java.util.Vector;
- import java.util.Random;
- import java.util.concurrent.TimeUnit;
- class NewThread implements Runnable {
- Random random;
- public static int randomNum;
- NewThread() {
- random = new Random();
- }
- public void run() {
- randomNum = random.nextInt(YourReaction.AmountOfCircles);
- YourReaction.circle[randomNum].setFill(Color.GREEN);
- try {
- Thread.sleep(2000);
- } catch(InterruptedException ie) {System.out.println("IE");}
- }
- }
- /*
- class ProcessThread implements Runnable {
- Random random;
- public static int randomNum;
- ProcessThread() {
- random = new Random();
- }
- public void run() {
- randomNum = random.nextInt(YourReaction.AmountOfCircles);
- YourReaction.circle[randomNum].setFill(Color.GREEN);
- }
- }*/
- public class YourReaction extends Application {
- Scene scene;
- VBox vbox;
- public static Circle[] circle;
- public static final int AmountOfCircles = 3;
- public final int radius = 20;
- public int score = 0;
- public static void main(String[] args) {
- launch(args);
- }
- public void start(Stage stage) {
- stage.setTitle("Hello World!");
- vbox = new VBox(5);
- scene = new Scene(vbox, 300, 250);
- stage.setScene(scene);
- Button B_Start = new Button("Start");
- Button B_Exit = new Button("Exit");
- B_Start.setOnMousePressed(new EventHandler<MouseEvent>() {
- public void handle(MouseEvent me) {
- GameProcess();
- }
- });
- B_Exit.setOnMousePressed(new EventHandler<MouseEvent>() {
- public void handle(MouseEvent me) {
- System.exit(0);
- }
- });
- vbox.setAlignment(Pos.CENTER);
- vbox.getChildren().addAll(B_Start, B_Exit);
- stage.show();
- }
- public int GameProcess() {
- vbox.getChildren().clear();
- HBox hbox = new HBox(5);
- hbox.setAlignment(Pos.CENTER);
- scene.setRoot(hbox);
- circle = new Circle[AmountOfCircles];
- for(int i = 0; i < AmountOfCircles; i++) {
- circle[i] = new Circle();
- circle[i].setRadius(radius);
- circle[i].setFill(Color.RED);
- hbox.getChildren().add(circle[i]);
- }
- Thread t = new Thread(new NewThread());
- while(score < 3) {
- t.start();
- circle[NewThread.randomNum].setOnMousePressed(new EventHandler<MouseEvent>() {
- public void handle(MouseEvent me) {
- circle[NewThread.randomNum].setFill(Color.RED);
- score++;
- }
- });
- /*
- try {
- Thread.sleep(timedir);
- } catch(InterruptedException ie) {System.out.println("Interrupted exception!");}*/
- }
- //eventThread.interrupt();
- return score;
- }
- }
Решение задачи: «Ошибка IllegalThreadStateException»
textual
Листинг программы
- package exp.dag;
- import javafx.application.Application;
- import javafx.event.EventHandler;
- import javafx.geometry.Pos;
- import javafx.scene.Scene;
- import javafx.scene.control.Button;
- import javafx.scene.input.MouseEvent;
- import javafx.scene.layout.HBox;
- import javafx.scene.layout.VBox;
- import javafx.scene.paint.Color;
- import javafx.scene.shape.Circle;
- import javafx.stage.Stage;
- import java.util.Random;
- class NewThread implements Runnable {
- public static int randomNum;
- Random random;
- NewThread() {
- random = new Random();
- randomNum = random.nextInt(YourReaction.AmountOfCircles); // лучше если это будет в конструкторе, иначе лишний код
- }
- public void run() {
- YourReaction.circle[randomNum].setFill(Color.GREEN);
- long startTime = System.currentTimeMillis();
- while (System.currentTimeMillis() - startTime < 2000 && !YourReaction.clicked) { // если еще нет двух секунд и игрок еще не нажал
- try {
- Thread.sleep(1);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
- public class YourReaction extends Application {
- public static final int AmountOfCircles = 3;
- public static Circle[] circle;
- static boolean clicked = false; // нажал на зеленую
- public final int radius = 20;
- public int score = 0;
- Scene scene;
- VBox vbox;
- public static void main(String[] args) {
- launch(args);
- }
- public void start(Stage stage) {
- stage.setTitle("Hello World!");
- vbox = new VBox(5);
- scene = new Scene(vbox, 300, 250);
- stage.setScene(scene);
- Button B_Start = new Button("Start");
- Button B_Exit = new Button("Exit");
- B_Start.setOnMousePressed(new EventHandler<MouseEvent>() {
- public void handle(MouseEvent me) {
- GameProcess();
- }
- });
- B_Exit.setOnMousePressed(new EventHandler<MouseEvent>() {
- public void handle(MouseEvent me) {
- System.exit(0);
- }
- });
- vbox.setAlignment(Pos.CENTER);
- vbox.getChildren().addAll(B_Start, B_Exit);
- stage.show();
- }
- public int GameProcess() {
- vbox.getChildren().clear();
- HBox hbox = new HBox(5);
- hbox.setAlignment(Pos.CENTER);
- scene.setRoot(hbox);
- circle = new Circle[AmountOfCircles];
- for (int i = 0; i < AmountOfCircles; i++) {
- circle[i] = new Circle();
- circle[i].setRadius(radius);
- circle[i].setFill(Color.RED);
- hbox.getChildren().add(circle[i]);
- }
- new Thread(() -> { // иначе у тебя не будет доступа к окну. программа ждала бы пока выполнится while, т.е. бесконечно
- while (score < 3) {
- Thread t = new Thread(new NewThread()); // ошибка была тут, перезапустить существующий поток не получится, придется создать новый и запустить его
- circle[NewThread.randomNum].setOnMousePressed(new EventHandler<MouseEvent>() {
- public void handle(MouseEvent me) {
- clicked = true;
- score++;
- }
- });
- clicked = false;
- t.start();
- try {
- t.join(); // ждет пока выполнится поток
- circle[NewThread.randomNum].setOnMousePressed(null); //
- circle[NewThread.randomNum].setFill(Color.RED);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }).start();
- //eventThread.interrupt();
- return score;
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д