面试遇到的笔试题,基本思路是每个线程计算1000个数的和,下面用两个方式实现:
1、利用线程池和Future获取每个线程的结果
package com.demo.test;
import java.util.concurrent.Callable;
public class CountThread implements Callable<Integer> {
public int begin;
public CountThread(int begin) {
this.begin=begin;
}
/**
* 求和
*/
@Override
public Integer call() throws Exception {
long result=0L;
for(int i=begin;i<=begin+999;i++) {
result=result+i;
}
return Integer.valueOf(String.valueOf(result));
}
}
package com.demo.test;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* 10个线程计算1-10000的和
* @author Administrator
*
*/
public class CountByThreadPool {
public static void main(String[] args) {
//10个定长线程
ExecutorService service=Executors.newFixedThreadPool(10);
Future<Integer> ret1=service.submit(new CountThread(1)); //计算1到1000
Future<Integer> ret2=service.submit(new CountThread(1001)); //计算1001到2000
Future<Integer> ret3=service.submit(new CountThread(2001));
Future<Integer> ret4=service.submit(new CountThread(3001));
Future<Integer> ret5=service.submit(new CountThread(4001));
Future<Integer> ret6=service.submit(new CountThread(5001));
Future<Integer> ret7=service.submit(new CountThread(6001));
Future<Integer> ret8=service.submit(new CountThread(7001));
Future<Integer> ret9=service.submit(new CountThread(8001));
Future<Integer> ret10=service.submit(new CountThread(9001));
try {
//50005000
System.out.println(ret1.get()+ret2.get()+ret3.get()+ret4.get()+ret5.get()
+ret6.get()+ret7.get()+ret8.get()+ret9.get()+ret10.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
2、利用CountDownLatch
package practice.thread;
import java.util.concurrent.CountDownLatch;
/**
* 利用Countdownlatch计数器多线求和
* @author Administrator
*
*/
public class Countdownlatch_count {
private int sum[]=new int[10];
public void calculate(int index,int j,CountDownLatch latch) {
for(int i=index;i<=(index+999);i++) {
sum[j]+=i;
}
将count值减1
latch.countDown();
System.out.println(Thread.currentThread().getName()+","+index+"到"+(index+999)+"和为:"+sum[j]);
}
/**
* 获取结果
* @return
*/
public int getSum() {
int sum1=0;
for(int item:sum) {
sum1+=item;
}
return sum1;
}
public static void main(String[] args) {
CountDownLatch latch=new CountDownLatch(10);
Countdownlatch_count count=new Countdownlatch_count();
for(int i=0;i<10;i++) {
final int j=i;
new Thread(new Runnable() {
@Override
public void run() {
count.calculate(j*1000+1, j, latch);
}
}).start();
}
try {
调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行
latch.await();
//和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行
//public boolean await(long timeout, TimeUnit unit) throws InterruptedException { };
}catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("1到10000的和为:"+count.getSum());
}
}
下面的连接介绍了Countdownlatch 和CyclicBarrier的区别,很形象
https://blog.csdn.net/zzg1229059735/article/details/61191679