两线程
一随机数组
一线程打印偶数下标和 二线程打印数组奇数下标和
打印两线程最终结果和
打印时间 执行时间
FutureTask<Integer>task1=new FutureTask<Integer>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int temp=0;
for (int i = 0; i <arrs.length ; i=i+2) {
temp +=arrs[i];
}
System.out.println("线程1:"+temp);
return temp;
}
});
Thread t1=new Thread(task1);
t1.start();/art
FutureTask<Integer> task2=new FutureTask<>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int temp=0;
for (int i = 1; i <arrs.length ; i=i+2) {
temp+=arrs[i];
}
System.out.println("线程2:"+temp);
return temp;
}
});
完整代码
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ThreadDemo15 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
long stime=System.currentTimeMillis();
//int[] arrs=new int[10000000];
int[] arrs=new int[4];
Random random=new Random();
for (int i = 0; i <arrs.length ; i++) {
int temp=random.nextInt(100)+1;
arrs[i]=temp;
//arrs[i]=(random.nextInt(100)+i);
System.out.println(temp);
}
FutureTask<Integer>task1=new FutureTask<Integer>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int temp=0;
for (int i = 0; i <arrs.length ; i=i+2) {
temp +=arrs[i];
}
System.out.println("线程1:"+temp);
return temp;
}
});
Thread t1=new Thread(task1);
t1.start();//start
FutureTask<Integer> task2=new FutureTask<>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int temp=0;
for (int i = 1; i <arrs.length ; i=i+2) {
temp+=arrs[i];
}
System.out.println("线程2:"+temp);
return temp;
}
});
Thread t2=new Thread(task2);
t2.start();
int sum=task1.get()+task2.get();
System.out.println("最终结果"+sum);
long etime=System.currentTimeMillis();
System.out.println("最终执行时间"+(etime-stime));
//t1.join();
//t2.join();
}
}
数组下标从零开始