【发布时间】:2016-05-19 21:23:41
【问题描述】:
我正在尝试准备简单的程序,它允许用户创建几个同时工作的任务。没什么特别的。每个任务都从值 1 开始,并在达到最大值时再加 1(每个任务都有不同的最大值)。然后任务通知,已达到指定值并停止。所有任务都必须包含在我所做的 ArrayList 中。我需要提供方法,允许(每时每刻)
- 检查任务状态
- 检查任务结果
- 单独完成任务,或全部完成
- 显示列表,其中包含所有任务(名称、值、状态)
我宁愿避免使用 gui,因为我的教授不需要它。我已经参与其中,但我不知道如何打印列表 (TASK_LIST) 的所有元素并停止单个任务。
MAIN.java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
Task t1 = new Task("Task 1", 2);
Task t2 = new Task("Task 2", 20);
Task t3 = new Task("Task 3", 5);
exec.execute(t1);
exec.execute(t2);
exec.execute(t3);
//showTASK_LIST();
}
}
TASK.java
import java.util.ArrayList;
import java.util.List;
class Task implements Runnable {
String TASK_NAME;
int TASK_RESULT;
int TASK_GOAL;
String TASK_STATUS;
static List<Task> TASK_LIST = new ArrayList<Task>();
public Task(String name, int goal) {
this.TASK_NAME = name;
this.TASK_GOAL = goal;
this.TASK_STATUS = "INACTIVE";
TASK_LIST.add(this);
}
public void run() {
TASK_STATUS="ACTIVE";
System.out.println(TASK_NAME + " starts.");
while (TASK_RESULT != TASK_GOAL){
//if (Thread.currentThread().isInterrupted()) return;
TASK_RESULT++;
System.out.println(TASK_NAME + " " + TASK_RESULT);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread.yield();
}
System.out.println("===========================================\n" +
TASK_NAME + " has been completed. Final result = " + TASK_GOAL +
"\n===========================================" );
setTASK_STATUS("COMPLETED");
System.out.println(TASK_LIST.size());
}
//Method to check current result
public int getTASK_RESULT() {
return TASK_RESULT;
}
//Method to check current status
public String getTASK_STATUS() {
return TASK_STATUS;
}
//Method to change result
public void setTASK_STATUS(String status) {
TASK_STATUS = status;
}
//This part doesnt work
public showTASK_LIST(){
for(int i = 0; i <= TASK_LIST.size(); i++){
System.out.println(TASK_LIST.get(i).TASK_NAME);
}
}
}
这就是它现在的样子。
【问题讨论】:
-
拨打
showTASK_LIST()会发生什么? -
mcve 会更容易回答这个问题
-
所以您还没有编写任何代码来将任务放入列表或实现任何请求的功能?我们可以回答您不理解的问题,但通常我们不会完成家庭作业。
-
@JimGarrison 我不同意。我将所有任务放在 ArrayList 中,并编写了程序的很大一部分。打印方法也几乎准备好了,我只是不知道在 main 中调用它应该是静态的。反正它已经解决了。
标签: java task java.util.concurrent