interrupt是用来停止用户线程的吗?下面是我遍的小程序,为什么在使用interrupt以后,线程frist和second仍然在运行
import java.io.*;public class TryThrea extends Thread {
private String fristName;
private String lastName;
private long awhile;
public static void main(String[] args) {
System.out.println("Enter while you hava had enough");
System.out.println("Strart.....");
TryThrea frist = new TryThrea("percy","Button",100L);
TryThrea second =new TryThrea("wallion","smith",200L);
frist.start();
second.start();
try{
System.in.read();
System.out.println("Enter had pressed,main() ending..");
frist.interrupt();
second.interrupt();
}catch(Exception e)
{
e.printStackTrace();
}
return;
}
public void run() {
while (true)
{
System.out.println(this.fristName);
try{
sleep(this.awhile);
}catch(Exception e)
{
e.printStackTrace();
}
System.out.println(this.lastName);
System.out.println("************");
}
} public TryThrea(String fristName ,String lastName,long delay)
{
this.fristName= fristName;
this.lastName = lastName;
this.awhile = delay;
//setDaemon(true);
}
}
import java.io.*;public class TryThrea extends Thread {
private String fristName;
private String lastName;
private long awhile;
public static void main(String[] args) {
System.out.println("Enter while you hava had enough");
System.out.println("Strart.....");
TryThrea frist = new TryThrea("percy","Button",100L);
TryThrea second =new TryThrea("wallion","smith",200L);
frist.start();
second.start();
try{
System.in.read();
System.out.println("Enter had pressed,main() ending..");
frist.interrupt();
second.interrupt();
}catch(Exception e)
{
e.printStackTrace();
}
return;
}
public void run() {
while (true)
{
System.out.println(this.fristName);
try{
sleep(this.awhile);
}catch(Exception e)
{
e.printStackTrace();
}
System.out.println(this.lastName);
System.out.println("************");
}
} public TryThrea(String fristName ,String lastName,long delay)
{
this.fristName= fristName;
this.lastName = lastName;
this.awhile = delay;
//setDaemon(true);
}
}
我想在first.start()之前使用frist.setDaemon(true),将其改成维护线程,而second线程仍然是用户线程的情况下,main线程关闭,frist和second线程都没有关闭,这是为什么?
谢谢,分不够可以再加:)
java工程师
java jsp servlet spring hibernate js css
上面会一部分既可qq 283765999
地点:北京
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html#interrupt()
interrrupt 使sleep送出一个exception,如果想使用interrupt来结束线程
可以将catch语句块放到run方法中的无限循环以外,这样就可以结束线程了
public void run() {
while (true)
{
System.out.println(this.fristName);
try{
sleep(this.awhile);
}
}catch(Exception e)
{
e.printStackTrace();
}