import java.util.*;
import java.net.*;
import java.io.*;
public class TimedUrlConnection implements Observer {
private URLConnection ucon = null;
private int time = 300000;//max time out
private boolean connected = false;
public TimedUrlConnection (URLConnection ucon,int time) {
this.ucon = ucon;
this.time = time;
}
public boolean connect() {
ObservableURLConnection ouc = new
ObservableURLConnection(ucon);
ouc.addObserver(this);
Thread ouct = new Thread(ouc);
ouct.start();
try {
ouct.join(time);
}
catch (InterruptedException i) {
//false, but should already be false
}
return(connected);
}
public void update(Observable o, Object arg) {
connected = true;
}//end of public void update(Observable o, Object arg)
}
class ObservableURLConnection extends Observable implements Runnable {
private URLConnection ucon;
public ObservableURLConnection(URLConnection ucon) {
this.ucon = ucon;
}//end of constructor
public void run() {
try {
ucon.connect();
setChanged();
notifyObservers();
}
catch (IOException e) {
}
}//end of public void run()
}//~~~~~~~~~~~~~~~~~~~Usage~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
URL url=new URL(someurlname);
URLConnection urlconn=url.openConnection();
TimedUrlConnection timeoutconn=new TimedUrlConnection(urlconn,100000);//time out: 100seconds
boolean bconnectok=timeoutconn.connect();
if(bconnectok==false)
{
//urlconn fails to connect in 100seconds
}
else
{
//connect ok
}

解决方案 »

  1.   

    Observer是什么接口??
    ObservableURLConnection怎么文档找不到这个类??
    编译可以通过了,我不太明白,请指教!!
      

  2.   

    class ObservableURLConnection extends Observable implements Runnable {
    ...
    }
    定义就在上面的代码中!
      

  3.   

    这个我看到了,刚才没留意,Observer观察器?由于某些对象的状态发生了改变,所以一组对象都需要更新,我在thinking in java看到这东西,有意思
      

  4.   

    运行结果:
    failed!
    java.net.UnknownHostException: www....
    thread ended!
    failed是在main方法里面打印出来结果,但是线程依然在运行,然后才输出UnknownHostException,还是没有按时断开连接啊       TimedUrlConnection timeoutconn=new TimedUrlConnection(urlconn,2000);//time out: 100seconds
           boolean bconnectok=timeoutconn.connect();
           if(bconnectok==false)
           {
               System.out.println("failed!");
           }
           else
           {
               System.out.println("connect ok");
           } 
      

  5.   

    ouct.join(time);是否关键呢?
    为什么等待线程ouct完成任务time
    的时间,线程还没有完成以后,为什么
    线程不能关闭呢????