import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;import org.apache.commons.collections.LRUMap;
import com.yang.system.util.HttpUtils;/**
*
* 实现对外部数据接口去取数据,并加载到缓存中,
* 另外实现定时更新功能
*/
public class CacheURL {
//缓存
Map nhwCache = null;
//更新线程
UpdateThreads updateThread = null;
public List nhwList = new ArrayList();
Object nhwlock = new Object();
private static CacheURL cu = null;
private CacheURL(){
nhwCache = Collections.synchronizedMap(new HashMap());
new UpdateThreads(this,7).start();
}
public static synchronized CacheURL getInstance() {
if (cu == null) {
cu = new CacheURL();
}
return cu;
} Worldsort getWorldsort() {
Worldsort wsort = null;
String wd = "wd";
if (nhwCache.containsKey(wd)){
wsort = (Worldsort)nhwCache.get(wd);
if(null!=wsort)
{
if((System.currentTimeMillis() - wsort.timestamp) > 60 * 1000 * 60 * 12)
{
updateNHW(wd);
}
}
}
else
{
updateNHW(wd);
}
synchronized(wd)
{
wsort = (Worldsort)nhwCache.get(wd);
if (wsort==null){
try{
wd.wait(100);
}catch (InterruptedException e){
}
}
}
return wsort;
}
public void updateNHW(String type) {
synchronized(nhwList) {
if (!nhwList.contains(type))
nhwList.add(type);
nhwList.notify();
}
}
public List getUpdateNHW(){
synchronized(nhwList){
try{
if (nhwList.size() == 0)
nhwList.wait();
if (nhwList.size()>0)
return nhwList;
}
catch(Exception e){
}
return null;
}
}
}class UpdateThreads extends Thread {
CacheURL parent = null;
int type = 0;
public UpdateThreads(CacheURL parent,int type){
this.type = type;
this.parent = parent;
}
public void run(){
while(true){
try{
switch(type)
{
case 7:
List nhwLists = parent.getUpdateNHW();
for(int i = 0;i < nhwLists.size(); i++)
{
String type = (String)nhwLists.get(i);
if(type!=null){
if(type.equals("na")){
Nasdaq na = getNasdaqWithURL();
if(null != na)
{
synchronized (parent.nhwlock)
{
parent.nhwCache.put("na", na);
parent.getUpdateNHW().remove("na");
}
}
}
if(type.equals("hk")){
Hkso hk = getHKstocksort();
if(null != hk)
{
synchronized (parent.nhwlock)
{
parent.nhwCache.put("hk", hk);
parent.getUpdateNHW().remove("hk");
}
}
}
if(type.equals("wd")){
Worldsort wd = getWorldsort();
if(null != wd)
{
synchronized (parent.nhwlock)
{
parent.nhwCache.put("wd", wd);
parent.getUpdateNHW().remove("wd");
}
}
}
}
}
//synchronized (nhwLists){
// nhwLists.notify();
//}
break;
}
}
catch (Exception e){
try{
sleep(5000);
}catch (Exception e1){
}
}
}
}
private Worldsort getWorldsort(){
Worldsort wd = new Worldsort();
//取数据
wd.content = HttpUtils.getResponseFromHttp("http://finance.qq.com/c/sjgz.htm");
wd.timestamp = System.currentTimeMillis();
return wd;
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货