Java Thread 不会运行,除非我把 Thread.sleep(1);



我有一段练习代码,当用户在键盘上输入代码时,它应该接受1010作为代码。不断检查代码是否正确输入的线程不会运行,除非我在run()中输入Thread.sleep(1);

我想知道这背后的原因是什么。

第1类:

import java.util.Scanner;
public class Class1 {
private static boolean valid = true, accepted = false, exit = false;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
newThread t1 = new newThread();
t1.start();
do {
try {
int code = Integer.parseInt(input.nextLine());
if(code == 1010)
accepted = true;
else
System.out.println("Please try again!");
}catch(Exception e) {
System.out.println("Please try again!");
}
}while(!exit);
}
public static boolean getValid() {
return valid;
}
public static void setValid(boolean input) {
valid = input;
}
public static boolean getAccepted() {
return accepted;
}
public static void setAccepted(boolean input) {
accepted = input;
}
}

新线程:


public class newThread extends Thread{
public void run() {
do {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(Class1.getAccepted())
Class1.setValid(false);
}while(Class1.getValid());
System.out.println("Code accepted");
}
}

预期没有Thread.sleep(1);

1010
Code accepted

实际结果:

1010

没有睡眠,newThread 会消耗所有 CPU,并且没有自然断点。在 Java语言规范你可以阅读更多关于它的信息。

最新更新