run()里的和main()里的catch()都各自应在什么时候发生?是不是run里的catch是在sleep的过程中被人打扰(比如join(3000)),就抛出?main()的catch是不是有人打扰join(3000)时才抛出的?
本例用了join(3000),在run里是sleep(4000),如果这时抛出异常,是抛run里的还是main()的?为什么?
/*
* TestJoin2.java
*
* Created on September 25, 2002, 12:08 PM
*/package ch18;/**
*
* @author Stephen Potts
*/
public class TestJoin2 extends Thread
{
/** Creates a new instance of TestJoin2 */
public TestJoin2()
{
}
public void run()
{
try
{
for ( int i=0; i<5; i++)
{
System.out.println("running the first loop " + i);
}
Thread.sleep(5000);
for ( int i=6; i<10; i++)
{
System.out.println("running the second loop" + i);
}
}catch (InterruptedException ie)
{
System.out.println("Sleep interrupted in run()");
}
}
public static void main(String[] args)
{
try
{
TestJoin2 t2 = new TestJoin2();
Thread t = new Thread(t2);
t.start();
t.join(3000);
for ( int i=11; i<15; i++)
{
System.out.println("running the third loop" + i);
}
}catch (InterruptedException ie)
{
System.out.println("Join interrupted in run()");
}
System.out.println("Exiting from Main");
}
}
本例用了join(3000),在run里是sleep(4000),如果这时抛出异常,是抛run里的还是main()的?为什么?
/*
* TestJoin2.java
*
* Created on September 25, 2002, 12:08 PM
*/package ch18;/**
*
* @author Stephen Potts
*/
public class TestJoin2 extends Thread
{
/** Creates a new instance of TestJoin2 */
public TestJoin2()
{
}
public void run()
{
try
{
for ( int i=0; i<5; i++)
{
System.out.println("running the first loop " + i);
}
Thread.sleep(5000);
for ( int i=6; i<10; i++)
{
System.out.println("running the second loop" + i);
}
}catch (InterruptedException ie)
{
System.out.println("Sleep interrupted in run()");
}
}
public static void main(String[] args)
{
try
{
TestJoin2 t2 = new TestJoin2();
Thread t = new Thread(t2);
t.start();
t.join(3000);
for ( int i=11; i<15; i++)
{
System.out.println("running the third loop" + i);
}
}catch (InterruptedException ie)
{
System.out.println("Join interrupted in run()");
}
System.out.println("Exiting from Main");
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货