加个时间的限制,如果在规定的时间内不能完成任务,就中断返回long delay = 15000; //15秒
java.util.Timer t = new java.util.Timer(); //由于java.swing.*中也有Timer
try{
t.schedule(new TimerTask(){
public void run(){
button.setEnabled(false);//这里改为中断程序返回的方法
}
}
, delay);
}catch(Exception e){}
java.util.Timer t = new java.util.Timer(); //由于java.swing.*中也有Timer
try{
t.schedule(new TimerTask(){
public void run(){
button.setEnabled(false);//这里改为中断程序返回的方法
}
}
, delay);
}catch(Exception e){}
不过new TimerTask(){
public void run(){
throw(new timeOutException());//这里改为中断程序返回的方法
}
}
会好些,那么这个TimerTask会不会跟我上面的URLConnection 方法一起运行?
在 run()方法中写联接过程
用线程的join(timeout)方法来控制运行时间。
事实上,这段代码就在run方法里面调用到的,
那么join(timeout)如何控制时间呢?
怎么写|?
import java.net.*;public class urlOpenerTest
{ public static void main(String[] args)
{ String host;
if (args.length > 0) host = args[0];
else host = "http://www.csdn.net"; int timeout = 5000;
StringBuffer s = urlOpener.openURL(host, timeout);
if (s == null)
System.out.println("The url could not be opened.");
else
System.out.println(s.toString());
}
}class urlOpener implements Runnable
{
public static StringBuffer openURL(String aHost, int timeout)
{
urlOpener opener = new urlOpener(aHost);
Thread t = new Thread(opener);
t.start();
try
{
t.join(timeout);
}
catch (InterruptedException exception)
{
}
return opener.getContent();
} public urlOpener(String aHost)
{
host = aHost;
content = null;
}
public StringBuffer getContent()
{ return content;
} public void run()
{ try
{
System.out.println(host);
URL siteInfo= new URL(host);
URLConnection conn = siteInfo.openConnection();
InputStream inputs = conn.getInputStream();
BufferedReader bf= new BufferedReader(new InputStreamReader(inputs));
String nextLine;
content = new StringBuffer();
//保存前十行
for(int i=0; i<10; i++){
if((nextLine = bf.readLine())!=null)
content.append(nextLine + "\n");
}
inputs.close();
}
catch(Exception e)
{
System.out.println("error: "+e);
}
}
private StringBuffer content;
private String host;
}
t是不是就结束了呢?
参见API说明:
join(long millis)
Waits at most millis milliseconds for this thread to die.