在開關盒中出現錯誤 - > RUNNING,ABORTED和READY無法解析爲變量。我能做些什麼來使它工作?試過枚舉,但它確實沒有工作。將字符串作爲開關盒
主類,我不能編輯:
public class Main {
public static void main(String[] args) throws InterruptedException {
StringTask task = new StringTask("A", 70000);
System.out.println("Task " + task.getState());
task.start();
if (args.length > 0 && args[0].equals("abort")) {
/*<- code that interrupts task after 1 sec and start a new thread
*/
}
while (!task.isDone()) {
Thread.sleep(500);
switch(task.getState()) {
//error case RUNNING: System.out.print("R."); break;
//error case ABORTED: System.out.println(" ... aborted."); break;
//error case READY: System.out.println(" ... ready."); break;
default: System.out.println("unknown state");
}
}
System.out.println("Task " + task.getState());
System.out.println(task.getResult().length());
}
}
StringTask類:
public class StringTask implements Runnable {
String string;
String result = "";
String status = "";
int x;
boolean end = false;
boolean done = false;
public StringTask(String string, int x) {
this.string = string;
this.x = x;
this.status = "CREATED";
}
public void start() {
Thread thread = new Thread(this);
thread.start();
}
public void run() {
this.status = "RUNNING";
synchronized (this.result) {
try {
for (int i = 0; i < x; i++) {
result += string;
}
this.status = "READY";
this.done = true;
} catch (Exception ex) {
this.status = "ABORTED";
this.done = false;
}
}
}
public void abort() {
this.end = true;
this.done = true;
this.status = "ABORTED";
Thread.interrupted();
}
public StringTask() {
this.status = "ABORTED";
}
public String getState() {
return this.status;
}
public boolean isDone() {
return this.done;
}
public String getResult() {
return this.result;
}
}
你會做的更好,如果你定義的狀態爲'enum'比爲字符串。無論如何,如果你想打開字符串,看看這個[指南](http://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html)。 – RealSkeptic