日期:2014-05-19  浏览次数:20603 次

急急急!!!多线程的分析,今天要做完,大侠来帮忙分析下。谢了!
我要写这么一个多线程
方法里面有一个list list里面保存了链接服务器的方法 假如有10台服务器的IP PORT等
我要链接这10台服务器,运行完代码之后就休息五分钟,五分钟之后继续链接 这样循环。
以前没弄过线程 多线程之类的。大侠帮我分析下。谢了!

------解决方案--------------------
for example
Java code
class Share implements Runnable {
    List<String> list;
    int index = 0;
    int count = 0;
    public Share(List<String> list) {
        this.list = list;
        count = list.size();
    }

    public void run() {
        while (true) {
            try {
                String url = null;
                synchronized(list) {
                    url = list.get(index);
                    index = (index+1)%count;
                }

                //do your process here
                
                Thread.sleep(1000*60*5);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

public class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        for (int i=0; i<10; i++) {
            list.add("xxx.xxx.xxx:port");
        }

        Runnable r = new Share(list);
        for (int i=0; i<20; i++) {
            Thread t = new Thread(r);
            t.start();
        }
    }
}

------解决方案--------------------
探讨

url = list.get(index);
index = (index+1)%count;

这两句话也不明白是什么意思

------解决方案--------------------
那是因为这个构造函数的原因:
public Share(List<String> list) {
this.list = list;
count = list.size();
}
需要创建一个Share的对象,需要一个list