java中两个线程同时运行,如何在一个线程抛出异常时将两个线程同时中断或结束,而不运行之后的代码块

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 {
public static void main(String[] args){
MyTask t1 = new MyTask("1");
MyTask t2 = new MyTask("s");
t1.start();
t2.start();
try{
t1.join();
t2.join();
if(t1.getIsEnd()&&t2.getIsEnd()){
System.out.println("zzzz");
}
}catch(InterruptedException e) {
}
}
}
class MyTask extends Thread {
private String s=null;
private boolean isEnd=false;
public MyTask(String s){
this.s=s;
}
public void run() {
System.out.println(Integer.parseInt(s));
System.out.println(s);
isEnd=true;
}
public boolean getIsEnd(){
return isEnd;
}
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-04-18
trycatch如果抛出异常的话是不运行try块里的, 转到运行catch块里
然后继续运行catch块后面的代码
如果是要问如何不运行catch后面的代码, 可以在catch里return

你描述的太不清楚了..
t1抛出异常按理说应该是在线程中捕获的, run方法是无法在向外抛异常的, 你的主线程里是不可能捕获到t1产生的异常的.
如果你要问t1中如何中断t2, 那要看你代码是如何写的, while循环还是wait还是其他什么样的.
第2个回答  2013-04-18

 给你代码,这是一种方法。
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;
}
}
}
}

第3个回答  2013-04-18
最简单的方法是在t1或者t2中catch住异常,然后执行System.exit(0)。保证程序直接中断,不执行下面的操作了
第4个回答  2013-04-18
你method()实在主线程里执行的 跟你别的线程又没关系
相似回答