threadisstarting...Threadisrunning...Threadisrunning...Threadisrunning...Threadisrunning...Threadisrunning...Askingthreadtostop...java.lang.InterruptedException:sleepinte...
thread is starting ...
Thread is running ...
Thread is running ...
Thread is running ...
Thread is running ...
Thread is running ...
Asking thread to stop...
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at InterruptThreadTest.run(InterruptThreadTest.java:11)
Thread is interupted...
Thread exiting under request...
stopping application...
代码如下:
public class InterruptThreadTest extends Thread
{
private boolean blockFlag=false;
public void run()
{
while(!blockFlag)
{
System.out.println("Thread is running ...");
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
System.out.println("Thread is interupted...");
}
}
System.out.println("Thread exiting under request...");
}
public static void main(String args[]) throws Exception
{
InterruptThreadTest thread=new InterruptThreadTest();
System.out.println("thread is starting ...");
thread.start();
try
{
Thread.sleep(5000);
System.out.println("Asking thread to stop...");
thread.blockFlag=true;
thread.interrupt();
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println("stopping application...");
}
}
展开