多线程并发处理数据简单的demo
package cn.test.dxc;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class test {
static int[] arr = new int[10];
static int index = 0;
static void cal1(int ix){
int sum = 0;
for (int i = ix*10+1; i <=(ix+1)*10 ; i++) {
sum +=i;
}
arr[ix]=sum;
index++;
System.out.println(Thread.currentThread().getName()+"cal1的方法的值:"+sum);
}
static void cal2(int ix){
int sum=0;
for (int i = 0; i <100 ; i+=10) {
sum +=i+ix+1;
System.out.println(Thread.currentThread().getName()+":"+sum);
}
arr[ix] = sum;
index++;
}
static int cal3(int ix){
int sum=0;
for (int i = 0; i <100 ; i+=10) {
sum +=i+ix+1;
System.out.println(Thread.currentThread().getName()+":"+sum);
}
return sum ;
}
static class Sum implements Runnable{
private int ix;
public Sum(int ix) {
this.ix = ix;
}
@Override
public void run() {
cal2(ix);
}
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
//方法一:开十条线程,并且让10条线程都执行完,用的是join,但是按照顺序的
// Thread[] threads = new Thread[10];
// for (int i = 0; i <threads.length ; i++) {
// threads[i] = new Thread(new Sum(i));
// threads[i].start();
// threads[i].join();
// }
ExecutorService service = Executors.newFixedThreadPool(10);
//方法二:使用callable,执行也是按照顺序来的,没有实现并发
// for (int i = 0; i <arr.length ; i++) {
// final int _i = i;
// arr[i]=service.submit(new Callable<Integer>() {
// @Override
// public Integer call() throws Exception {
// return cal3(_i);
// }
// }).get();
// }
//方法三:用runable做可以实现并发
// for (int i = 0; i <arr.length ; i++) {
// service.submit(new Sum(i));
// }
// //如果没有等1s,线程执行不完计算值出错
// while(index<10){
// Thread.sleep(1000);
// }
//方法四:也是实现runable,但是是查看线程池中的线程是否都执行完。
for (int i = 0; i <arr.length ; i++) {
service.submit(new Sum(i));
}
service.shutdown();
while(true){
if(service.isTerminated()){
System.out.println("所有的子线程都结束了!");
break;
}
}
//计算总值
int sum = 0;
for (int i = 0; i <arr.length ; i++) {
sum += arr[i];
}
System.out.println("最终结果为"+sum);
}
}