方法一:使用线程池:
package demo_0805_thread;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Sum {
static int n = 10;// 线程数
static long start = 1L;// 开始值
static long end = 100L;// 结束值
static long sum = 0L;
public Sum(int n, long start, long end, long sum) {
super();
n = 10;// 线程数
start = 1L;// 开始值
end = 100L;// 结束值
sum = 0L;
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
long startTime = System.currentTimeMillis();
ExecutorService threads = Executors.newFixedThreadPool(n);
CompletionService<Long> cs = new ExecutorCompletionService<Long>(threads);
for (int i = 0; i < n; i++) {
cs.submit(new SumFun(start, end, n, i));
}
threads.shutdown();// 关闭service
int i=0;
while(i<n) {
sum += cs.take().get();
i++;
}
long endTime = System.currentTimeMillis();
System.out.println("和:" + ",耗时:" + (endTime - startTime) + "ms");
}
}
class SumFun implements Callable<Long> {
private long start;
private long end;
public SumFun(long start, long end, int n, int index) {
this.start = index * (end - start) / n;
this.end = (index + 1) * (end - start) / n - 1;
if (index == 0) {
this.start = start;
}
if (index == n - 1) {
this.end = end;
}
}
@Override
public Long call() throws Exception {
long sum = 0;
for (long i = start; i <= end; i++) {
sum += i;
}
return sum;
}
}
方法二: 使用基本的多线程:
package demo_0805_thread;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test extends Thread {
static int n = 0;
private int startNum = 0;
private int sn;
public Test(int sn) {
this.startNum = sn;
}
static Lock lock = new ReentrantLock();
public static void addSum(int num) {
lock.lock();
try {
n += num;
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
long startTime = System.currentTimeMillis();
// 线程组启动
Thread[] thList = new Thread[10];
for (int i = 0; i < 10; i++) {
thList[i] = new Test(i * 10 + 1);
thList[i].start();
}
// 合并计算
for (int i = 0; i < 10; i++) {
thList[i].join();
}
System.out.println("Sum is : " + n);
long endTime = System.currentTimeMillis();
System.out.println("和:"+",耗时:"+(endTime-startTime)+"ms");
}
public void run() {
int sum = 0;
int i = 0;
do {
sum += sn + i;
i++;
} while (i < 10);
addSum(sum);
}
}
在这个方法二上,进一步可以使用条件变量处理