用线程控制访问请求URL超时问题

来源:互联网 发布:wsn数据融合技术研究 编辑:程序博客网 时间:2024/06/05 07:55
因为需要,公司要查看下面的子服务有没有开启,每页十个,但有些注册的url不正常,导致url解析要很久,长达10-20秒,受不了,所以上网查了下,改为线程...
//测试线程控制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();} }} 



	
				
		
原创粉丝点击