我要写这么一个多线程
方法里面有一个list list里面保存了链接服务器的方法 假如有10台服务器的IP PORT等
我要链接这10台服务器,运行完代码之后就休息五分钟,五分钟之后继续链接 这样循环。
以前没弄过线程 多线程之类的。大侠帮我分析下。谢了!
方法里面有一个list list里面保存了链接服务器的方法 假如有10台服务器的IP PORT等
我要链接这10台服务器,运行完代码之后就休息五分钟,五分钟之后继续链接 这样循环。
以前没弄过线程 多线程之类的。大侠帮我分析下。谢了!
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();
}
}
}
大概是明白了一点,但是只用sleep()休息五分钟之后 他会自动唤醒继续运行代码么?
index = (index+1)%count;这两句话也不明白是什么意思
这里是在原子操作地取得链接的url
sleep()休息五分钟之后会再执行一次,因为在while(true)里面。程序跑起来就一直执行。
url = list.get(index);
index = (index+1)%count;
}里面的这两句是锁上了对象之后运行的代码?
这句话里面 参数为什么是list?
public Share(List<String> list) {
this.list = list;
count = list.size();
}
需要创建一个Share的对象,需要一个list