thread t1 = new thread();
thread t2 = new thread();
t1.start();
t2.start();
t1.join();
t2.join();
method(执行代码块);
现在的情况是t1或者t2其中之一抛出异常后,依然会被正常运行的线程执行method代码块
如何在t1或者t2抛出异常时,不执行下面的method代码块...
没有太理想的方法 比较笨的办法是自己重新封装一次线程类 如下边的方法就是在run方法的最后一行修改一次状态,如果执行到最后那状态就会修改,如果出现异常执行不到最后状态就不修改
public class Dfdsfasdfasdfa { 给你代码,这是一种方法。
import java.util.Random;
public class Test {
public static void main(String[] args) throws Exception {
TestThread t1 = new TestThread("T1");
TestThread t2 = new TestThread("T2");
t1.start();
t2.start();
t1.join();
t2.join();
if (!t1.isException && t2.isException) {
System.out.println("abc");
}
}
}
class TestThread extends Thread {
private String name = null;
public boolean isException = false;
public TestThread(String name) {
this.name = name;
}
public void run() {
Random random = new Random();
isException = false;
while (true) {
try {
int ranInt = random.nextInt(500);
System.out.println(name + " is random : " + ranInt);
if (ranInt == 250) {
throw new Exception();
}
sleep(100);
} catch (Exception e) {
System.out.println(name + " is stop");
isException = true;
break;
}
}
}
}