我在 Java中开启一个线程 怎样安全杀死.当然不能用stop方法.Thread t = new Thread(){
public void run(){
URL m_URL = new URL( resourceURL );
HttpURLConnection connection = ( HttpURLConnection ) m_URL.openConnection();
connection.setConnectTimeout( 30000 );
connection.setDoInput( true );
InputStream input = connection.getInputStream();
}
};
t.start();我在网路不通的情况下,需要等待30秒才能 捕获然后结束线程,
我怎样在任何时候都能杀死这个线程呢 ?
如ScheduledThreadPoolExecutor,ThreadPoolExecutor等。
或ThreadPoolExecutor.shutdown()
public class Test extends Thread {
private String name;
public Test(String name) {
this.name = name;
}
public void write() {
System.out.print(name);
}
public static void main(String[]args) throws Exception{
Thread t1=new Test("myThread");
t1.start();
Scanner sc=new Scanner(System.in);
String s;
while((s=sc.next()).equals("stop")){
t1.interrupt();
break;
}
}
public void run() {
for(int i=0;;i++){
if(this.isInterrupted()){
System.out.println("exit*****************");
return;
}
write();
System.out.println(); }
}
}
java目前不建议直接自己结束进程,而是根据一定的条件结束进程。
你这个写吗基本上没法办,因为你这个额线程执行一次就退出了,结束执行只能造成一些问题。那些无限循环的还比较好办
java核心技术高级特性第一章就有写