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

因为需要,公司要查看下面的子服务有没有开启,每页十个,但有些注册的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 block
				System.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();
				} 
			}
		} 






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值