<pre name="code" class="java">public class ThreadRelatedService {
// key point: records list must be ordered
public void exec() {
// System.out.println("Start ThreadRelatedService.exec:");
List<String> list = new ArrayList<String>();
// if there are 91000 records in the table
for (int i = 0; i < 900000; i++) {
list.add(String.valueOf(i));
}
for (int i = 0; i < 9; i++) {
// get part records from table by page
List<String> sublist = list.subList(100000 * i, 100000 * (i + 1));
subExec(sublist);
}
// System.out.println("End ThreadRelatedService.exec:");
}
private void subExec(List<String> list) {
// System.out.println("Start ThreadRelatedService.subExec:");
Thread[] threadPool = new Thread[10];
for (int i = 0; i <= 9; i++) {
// divide one page data to parts for different thread to process
// subList(fromIndex,toIndex),data of toIndex will not be selected
List<String> sublist = list.subList(10000 * i, 10000 * (i + 1));
threadPool[i] = new Thread(new ThreadImpl(sublist), "Thread" + i);
threadPool[i].start();
}
for (Thread thread : threadPool) {
try {
thread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// System.out.println("End ThreadRelatedService.subExec:");
}
private class ThreadImpl implements Runnable {
private List<String> list;
public ThreadImpl(List<String> list) {
this.list = list;
}
@Override
public void run() {
// System.out.println("Thread" + Thread.currentThread().getId());
// System.out.println("Start ThreadRelatedService.run:");
String result = "";
for (String str : list) {
result += str + "_";
}
System.out.println(result);
// System.out.println("End ThreadRelatedService.run:");
}
}
}
java多线程并发处理
最新推荐文章于 2022-10-27 15:40:49 发布