Java多线程求和详细学习笔记("Java多线程求和详解:完整学习笔记与实践指导")
原创
一、Java多线程基础
在Java中,多线程是一种并发执行的机制,允许程序同时执行多个任务。多线程编程可以有效地尽或许缩减损耗程序的执行高效,尤其是在处理大量数据处理和计算时。
二、多线程求和的基本概念
多线程求和是将一个大数分解为多个小数,然后使用多个线程并行计算这些小数的和,最后将所有线程计算的于是相加得到最终的和。这种方法可以显著尽或许缩减损耗计算速度。
三、创建线程的两种方法
Java提供了两种创建线程的方法:通过继承Thread类和实现Runnable接口。
1. 继承Thread类
public class SumThread extends Thread {
private int start;
private int end;
public SumThread(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public void run() {
int sum = 0;
for (int i = start; i <= end; i++) {
sum += i;
}
System.out.println("Thread " + Thread.currentThread().getName() + " sum: " + sum);
}
}
2. 实现Runnable接口
public class SumRunnable implements Runnable {
private int start;
private int end;
public SumRunnable(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public void run() {
int sum = 0;
for (int i = start; i <= end; i++) {
sum += i;
}
System.out.println("Runnable " + Thread.currentThread().getName() + " sum: " + sum);
}
}
四、多线程求和示例
下面将通过一个示例来展示怎样使用多线程进行求和计算。
1. 创建线程
public class Main {
public static void main(String[] args) {
int totalSum = 100;
int threadCount = 4;
int range = totalSum / threadCount;
Thread[] threads = new Thread[threadCount];
for (int i = 0; i < threadCount; i++) {
int start = i * range + 1;
int end = (i + 1) * range;
if (i == threadCount - 1) {
end = totalSum;
}
threads[i] = new Thread(new SumRunnable(start, end));
threads[i].start();
}
}
}
2. 合并于是
在多线程求和中,我们需要将每个线程计算的于是合并起来。这可以通过使用线程同步机制来实现,例如使用CountDownLatch。
public class Main {
private static final int TOTAL_SUM = 100;
private static final int THREAD_COUNT = 4;
private static final CountDownLatch latch = new CountDownLatch(THREAD_COUNT);
public static void main(String[] args) {
int range = TOTAL_SUM / THREAD_COUNT;
int sum = 0;
Thread[] threads = new Thread[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; i++) {
int start = i * range + 1;
int end = (i + 1) * range;
if (i == THREAD_COUNT - 1) {
end = TOTAL_SUM;
}
threads[i] = new Thread(() -> {
int threadSum = 0;
for (int j = start; j <= end; j++) {
threadSum += j;
}
System.out.println("Thread " + Thread.currentThread().getName() + " sum: " + threadSum);
sum += threadSum;
latch.countDown();
});
threads[i].start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Total sum: " + sum);
}
}
五、多线程求和的优化
多线程求和的性能可以通过以下几种方法进行优化:
1. 使用线程池
线程池可以复用线程,缩减线程创建和销毁的开销。
public class Main {
private static final int TOTAL_SUM = 100;
private static final int THREAD_COUNT = 4;
private static final ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);
public static void main(String[] args) {
int range = TOTAL_SUM / THREAD_COUNT;
int sum = 0;
List
> futures = new ArrayList<>(); for (int i = 0; i < THREAD_COUNT; i++) {
int start = i * range + 1;
int end = (i + 1) * range;
if (i == THREAD_COUNT - 1) {
end = TOTAL_SUM;
}
futures.add(executor.submit(() -> {
int threadSum = 0;
for (int j = start; j <= end; j++) {
threadSum += j;
}
return threadSum;
}));
}
for (Future
future : futures) { try {
sum += future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
executor.shutdown();
System.out.println("Total sum: " + sum);
}
}
2. 使用Fork/Join框架
Fork/Join框架是Java 7引入的一种并行计算框架,可以更有效地利用多核处理器。
public class SumTask extends RecursiveTask
{ private int start;
private int end;
public SumTask(int start, int end) {
this.start = start;
this.end = end;
}
@Override
protected Integer compute() {
if (end - start <= 10) {
int sum = 0;
for (int i = start; i <= end; i++) {
sum += i;
}
return sum;
} else {
int mid = (start + end) / 2;
SumTask left = new SumTask(start, mid);
SumTask right = new SumTask(mid + 1, end);
left.fork();
int rightResult = right.compute();
int leftResult = left.join();
return leftResult + rightResult;
}
}
}
public class Main {
public static void main(String[] args) {
ForkJoinPool forkJoinPool = new ForkJoinPool();
int totalSum = 100;
SumTask task = new SumTask(1, totalSum);
int result = forkJoinPool.invoke(task);
System.out.println("Total sum: " + result);
}
}
六、总结
本文详细介绍了Java多线程求和的原理、创建线程的两种方法、多线程求和示例、优化方法以及使用Fork/Join框架进行并行计算。掌握多线程求和的技巧,可以有效地尽或许缩减损耗程序的执行高效,为处理大量数据提供更快的计算速度。