I would like to know if I did everything right and if there a way to do it more simple?
Task: Task link to html file
My main:
package zad2;
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")) {
/*
<- here add the code interrupting the task after a second
and run it in a separate thread
*/
Thread.sleep(500);
task.abort();
task.startNewTread();
}
while (!task.isDone()) {
Thread.sleep(500);
switch(task.getState()) {
case RUNNING: System.out.print("R."); break;
case ABORTED: System.out.println(" ... aborted."); break;
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());
}
}
My StringTask:
package zad2;
public class StringTask implements Runnable {
String line;
String letter;
int amount;
boolean isAborted;
TaskState stat;
boolean wasAborted = false;
public StringTask(String s, int i){
line = "";
letter = s;
amount = i;
stat = TaskState.CREATED;
isAborted = false;
}
public StringTask(String s){
this(s, 0);
}
@Override
public void run() {
while (amount > 0 && !isAborted){
line += letter;
amount--;
}
if(wasAborted == false) stat = TaskState.READY;
else stat = TaskState.ABORTED;
}
public String getResult (){
return line;
}
public TaskState getState (){
return stat;
}
public void start (){
isAborted = false;
stat = TaskState.RUNNING;
new Thread(this).start();
//System.out.println("start");
//run();
}
public void startNewTread (){
isAborted = false;
stat = TaskState.RUNNING;
new Thread(this).start();
}
public void abort (){
stat = TaskState.ABORTED;
wasAborted = true;
isAborted = true;
}
public boolean isDone(){
if (stat == TaskState.READY || stat == TaskState.ABORTED) return true;
return false;
}
}
My TaskState:
package zad2;
public enum TaskState {
CREATED, RUNNING, ABORTED, READY
}