问题:多线程任务,一个任务执行错误,其他任务应该同步取消
1.主线程监视
主线程监视任务线程,当一个任务线程出现执行错误时,直接调用System.exit(0)结束程序。
任务线程代码:
package com.example.thread.cancel.listener;
public class TaskThread extends Thread {
/**
* 线程名称
*/
public String name;
/**
* 模拟线程执行时长
*/
public int mockExecMillisecond;
/**
* 模拟线程执行结果
*/
public boolean mockExecStatus;
/**
* 线程实际执行结果
*/
public boolean defaultExecStatus = Boolean.TRUE;
/**
* 定义TaskThread构造方法,用于初始化TaskThread对象
* @param name 线程名称
* @param mockExecMillisecond 模拟线程执行时长
* @param mockExecStatus 模拟线程执行结果
*/
public TaskThread(String name, int mockExecMillisecond, boolean mockExecStatus) {
this.name = name;
this.mockExecMillisecond = mockExecMillisecond;
this.mockExecStatus = mockExecStatus;
}
@Override
public void run() {
try {
System.out.printf("%s开始执行\n", this.name);
Thread.sleep(mockExecMillisecond);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("%s执行结束,执行时间%sms,执行结果%s\n",
this.name, this.mockExecMillisecond, this.mockExecStatus);
defaultExecStatus = mockExecStatus;
}
}
主线程代码:
package com.example.thread.cancel.listener;
import java.util.ArrayList;
import java.util.List;
public class TaskListener {
public static void main(String[] args) {
List<TaskThread> taskThreads = new ArrayList<>();
TaskThread taskThreadOne = new TaskThread("taskOne",5000,true);
TaskThread taskThreadTwo = new TaskThread("taskTwo",3000,true);
TaskThread taskThreadThree = new TaskThread("taskThree",1000,false);
taskThreads.add(taskThreadOne);
taskThreads.add(taskThreadTwo);
taskThreads.add(taskThreadThree);
//线程启动
for (TaskThread taskThread : taskThreads) {
taskThread.start();
}
//模拟监听,通过任务线程的状态判断线程执行结果,并进行相应处理
for (;;){