我有Java主类,在类中,我启动一个新线程,在主,它等待直到线程死亡.在某些时刻,我从线程中抛出一个运行时异常,但是我无法捕获从主类中的线程抛出的异常.
这是代码:
public class Test extends Thread
{
public static void main(String[] args) throws InterruptedException
{
Test t = new Test();
try
{
t.start();
t.join();
}
catch(RuntimeException e)
{
System.out.println("** RuntimeException from main");
}
System.out.println("Main stoped");
}
@Override
public void run()
{
try
{
while(true)
{
System.out.println("** Started");
sleep(2000);
throw new RuntimeException("exception from thread");
}
}
catch (RuntimeException e)
{
System.out.println("** RuntimeException from thread");
throw e;
}
catch (InterruptedException e)
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
谁知道为什么?
假设从main方法启动一个线程.如果在线程中抛出异常但在线程内没有处理异常会发生什么?
是否可以将异常传播回main方法?
我不明白为什么线程InterruptedException在中断时不会抛出.
我正在尝试使用以下代码段:
公共类InterruptTest {
Run Code Online (Sandbox Code Playgroud)public static void main(String[] args) { MyThread t = new MyThread(); t.start(); try { t.join(); } catch (InterruptedException ex) { ex.printStackTrace(); } } private static class MyThread extends Thread { @Override public void run() { Thread.currentThread().interrupt(); } } }
在API文档中,它在interrupt()方法上说:
如果在调用Object类的wait(),wait(long)或wait(long,int)方法或Thread.join(),Thread.join(long),Thread的方法中阻止此线程. join(long,int),Thread.sleep(long)或Thread.sleep(long,int),这个类的方法,然后它的中断状态将被清除,它将收到InterruptedException.
在Java中,如果我从A类中的main方法开始一个线程T,并且在T中发生异常,那么A中的main方法将如何知道这一点.如果我没有错,A类的实例和线程T将出现在两个独立的堆栈中,对,那么,线程的父节点如何知道异常?
难道在Android中有一个"抛出"东西的AsyncTask吗?如果我不@Override方法,它不会被调用.如果我在末尾添加"throws",则会出现编译器错误.例如,我想做类似的事情:
class testThrows extends AsyncTask<String,Void,JSONObject> {
@Override
protected JSONTokener doInBackground(<String>... arguments) throws JSONException {
String jsonString = arguments[0];
JSONTokener json = new JSONTokener(jsonString);
JSONObject object = json.getJSONObject("test");
return object;
}
}
Run Code Online (Sandbox Code Playgroud)
json.getJSONObject抛出JSONException.有没有办法做到这一点?
我正在编写一个将使用多个线程的应用程序.有一个主线程正在启动另一个线程.我想要实现的是当其中一个启动的线程抛出异常时,主线程应该停止启动线程.它看起来或多或少像这样:
class SomeClass {
boolean launchNewThread = true;
public static void main() {
while (launchNewThread) {
try {
AnotherClass.run();
} catch (CrossThreadException e) {
launchNewThread = false;
}
}
}
}
class AnotherClass implements Runnable {
public void run() {
if (a=0) throw new CrossThreadException();
}
Run Code Online (Sandbox Code Playgroud)
}