【发布时间】:2017-04-10 21:30:24
【问题描述】:
在 switch 情况下存在错误 -> 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,而不是字符串,您会做得更好。无论如何,如果你想打开字符串,看看这个guide。
标签: java string multithreading switch-statement