62,621
社区成员
发帖
与我相关
我的任务
分享
package com;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MoveDataCurr {
List<OldDBPlanVersion2> totalList = new ArrayList<OldDBPlanVersion2>();
Logger log = LoggerFactory.getLogger(MoveDataCurr.class);
AtomicInteger atomic = new AtomicInteger(0);
public static void main(String[] args) throws Exception {
MoveDataCurr md = new MoveDataCurr();
md.moveData();
}
public void moveData() throws Exception {
try {
openThread();
OldDBPlanVersion2 d;
Random rr = new Random();
while (true) {
List<OldDBPlanVersion2> dbList = new ArrayList<OldDBPlanVersion2>();
for (int i = 0; i < 20; i++) {
d = new OldDBPlanVersion2();
dbList.add(d);
}
Thread.sleep(Math.abs(rr.nextInt() % 100));
synchronized (totalList) {
log.error("in " + Thread.currentThread().getName());
totalList.addAll(dbList);
log.error("out " + Thread.currentThread().getName());
}
}
} catch (Exception e) {
log.error("出错", e);
}
while (atomic.get() > 0) {
Thread.sleep(10000);
}
}
private void openThread() {
for (int i = 0; i < 5; i++) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
dealinThread();
} catch (Exception e) {
log.error(
Thread.currentThread().getName()+ " ......a thread error,size:"+ totalList.size() ,
e);
System.exit(-1);
}
atomic.addAndGet(-1);
}
};
atomic.addAndGet(1);
Thread t = new Thread(r);
t.start();
}
}
private void dealinThread() throws Exception {
List<OldDBPlanVersion2> my;
int len;
Random rr = new Random();
while (true) {
my = null;
synchronized (totalList) {
log.error("in " + Thread.currentThread().getName());
len = totalList.size();
if (len > 200) {
my = totalList.subList(0, 200);
totalList.removeAll(my);
} else if (len > 0) {
my = new ArrayList<OldDBPlanVersion2>();
my.addAll(totalList);
totalList.clear();
}
log.error("out " + Thread.currentThread().getName());
}
Thread.sleep(Math.abs(rr.nextInt() % 1000));
}
}
}
class OldDBPlanVersion2 {
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}