本人写一个小测试,构想是开一条主线程不断循环扫数据库中的任务,每拿到一条任务开2个子线程分发给500个用户,
我的想法是在子线程的构造参数里面把所有用户传入,然后run方法里面加同步块来控制用户的减少,每发送一个用户就把该用户移除,但是现在不会同步这一块,求助,贴上代码:
MainThread
public class ScanDB implements Runnable{
public void run() {
List list1=new ArrayList();
List list2=new ArrayList();
for(int t=0;t<3;t++){
for (int j=0;j<10;j++){
list2.add("用户"+(t*10+j));
}
list1.addAll(list2);
}
childThread childThread=new childThread(list1,1);
childThread childThread2=new childThread(list1,1);
Thread t1=new Thread(childThread);
t1.setName("Thread1");
t1.start();
Thread t2=new Thread(childThread2);
t2.setName("Thread2");
t2.start();
}
}
ChildThread:
public class childThread implements Runnable{
private List users;
private int schdule;
private int count;
public childThread(List<String> users, int schdule) {
this.users = users;
this.schdule = schdule;
this.count=users.size();
}
public void run() {
while (count>0) {
sendMail();
}
}
private void sendMail(){
//求助部分
count--;
}
}