我们经常可能会遇到数据迁移,比如重某个表迁移至另外一个表,可能会有如下场景
1.数据已知清楚明确,比如时间划分明确,我们可以设定多少个线程,每个线程处理不同时间段的数据即可,相对来说比较简单,每个线程处理自己需要处理的数据即可,记录已处理的数据游标以及时间段。 2.根据主键排序处理,每个线程需要获取到当前已处理的游标位置,也就是主键索引位置,此值是需要同步的等待的;以下有两种方法 2.1 当一个线程正在读区到数据,也就是数据准备阶段,那么其他线程得等待当前线程修改修改游标索引 2.2 获取到当前游标锁的线程即马上计算游标位置同步修改,释放锁;
以上2.2方法优于方法2.1,不需要等待其他线程获取数据阶段,只需要等获取锁的线程计算完游标位置即可,不过以下代码是通过2.1的方法实现的;
// 记录当前线程处理游标
volatile static Integer index = 0;
// 模拟缘数据
static List<Integer> data = new ArrayList<Integer>(90000000);
// 处理标记
volatile static boolean flag = true;
static class ThreadA extends Thread {
String threadName;
CountDownLatch latch;
public ThreadA(String threadName, CountDownLatch latch) {
this.threadName = threadName;
this.latch = latch;
}
@Override
public void run() {
while (flag) {
List<Integer> s = null;
synchronized (index) {
// 每次处理100000
if (index + 1000001 >= data.size()) {
flag = false;
int left = data.size() - index;
s = data.subList(index, index + left);
} else {
s = data.subList(index, index + 1000001);
}
index = s.get(s.size() - 1);
}
if (true) {
try {
// 数据处理业务模拟
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("threadName:=" + threadName
+ " copy data to table B to leng"
+ s.get(s.size() - 1));
}
}
latch.countDown();
}
}
public static void main(String[] args) throws InterruptedException {
long startTime = System.currentTimeMillis();
for (int i = 0; i < 20000000; i++) {
data.add(i);
}
long endTime = System.currentTimeMillis();
System.out.println("spend second:=" + (endTime - startTime) / 1000);
CountDownLatch latch = new CountDownLatch(1);// 两个工人的协作
ThreadA a = new OtherTest.ThreadA("A", latch);
ThreadA b = new OtherTest.ThreadA("B", latch);
startTime = System.currentTimeMillis();
a.start();
b.start();
latch.await();
endTime = System.currentTimeMillis();
System.out.println("copy data spend secdon:=" + (endTime - startTime)
/ 1000);
}