//测试线程控制url超时问题public static void testThreadUrl(){String t="http://tg, http://172.17.16.100:8180/suite, http://172.17.16.124:8280/suite,http://tyty, http://172.17.16.100:8380/suite, http://172.17.16.124:8280/suite, http://4545rtrt, http://172.17.16.160:8280/suite, http://ghhg, http://uyjh";String[] s=t.split(",");long start=0;long start2=System.currentTimeMillis(); for(String u:s){start=System.currentTimeMillis();URL url;try {url = new URL(u);URLConnection urlconn=url.openConnection(); TimedUrlConnection timeoutconn=new TimedUrlConnection(urlconn,500);//time out: 100seconds boolean bconnectok=timeoutconn.connect(); System.out.println("请求URL一次需要:"+(System.currentTimeMillis()-start)+"毫秒"); if(bconnectok==false) { //urlconn fails to connect in 100seconds System.out.println("false");} else { //connect ok System.out.println("OK");}} catch (Exception e) {// TODO Auto-generated catch blockSystem.out.println("失败请求URL一次需要:"+(System.currentTimeMillis()-start)+"毫秒");} }System.out.println("总共:"+(System.currentTimeMillis()-start2));}}
//用线程控制url连接超时的问题(观察者模式) class TimedUrlConnection implements Observer { private URLConnection conn = null; private int time = 300000;//max time out private boolean connected = false; public TimedUrlConnection (URLConnection conn, int time) { this.conn = conn; this.time = time; } public boolean connect() {ObservableURLConnection ouc = new ObservableURLConnection(conn); ouc.addObserver(this); //监听Thread thread = new Thread(ouc); thread.start(); try { thread.join(500); } catch (InterruptedException i) { //false, but should already be false i.printStackTrace();} return (connected); } public void update(Observable o, Object arg) { connected = true; }} class ObservableURLConnection extends Observable implements Runnable { private URLConnection conn; public ObservableURLConnection(URLConnection conn) { this.conn = conn; }public void run() {try { conn.connect(); //只有在setChange()被调用后,notifyObservers()才会去调用update()。setChanged(); notifyObservers(); } catch (Exception e) { e.printStackTrace();} }}