Java多线程实现1到100相加
时间: 2023-03-28 19:03:29 浏览: 149
可以使用多线程实现1到100相加,具体实现方式可以使用线程池来管理多个线程,每个线程负责计算一部分数字的和,最后将所有线程计算的结果相加即可得到1到100的总和。具体代码实现可以参考Java中的Executor框架。
相关问题
java多线程实现0到100相加
好的,以下是Java多线程实现0到100相加的示例代码:
```java
public class SumThread extends Thread {
private int start;
private int end;
private int sum;
public SumThread(int start, int end) {
this.start = start;
this.end = end;
}
public void run() {
for (int i = start; i <= end; i++) {
sum += i;
}
}
public static void main(String[] args) throws InterruptedException {
int n = 100;
int threadCount = 5;
int step = n / threadCount;
SumThread[] threads = new SumThread[threadCount];
for (int i = 0; i < threadCount; i++) {
threads[i] = new SumThread(i * step + 1, i * step + step);
threads[i].start();
}
int sum = 0;
for (int i = 0; i < threadCount; i++) {
threads[i].join();
sum += threads[i].sum;
}
System.out.println("0到" + n + "的和为:" + sum);
}
}
```
以上代码中,我们使用了继承 Thread 类的方式来创建多线程,并将任务拆分成多个子任务分别计算,最后将所有子任务的结果相加得到最终结果。在主线程中,我们使用 join() 方法等待所有子线程完成,然后将它们的结果相加。注意,我们需要将任务拆分成多个子任务,并在子任务中计算结果,以充分利用多线程的优势。
总体上来说,这是一个简单的示例,实际中需要根据具体情况进行适当的修改和优化。
java多线程查询list
以下是Java多线程查询List的示例代码:
```java
import java.util.ArrayList;import java.util.List;
import java.util.concurrent.*;
public class MultiThreadListSearch {
public static void main(String[] args) throws InterruptedException, ExecutionException {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 100000; i++) {
list.add(i);
}
ExecutorService executorService = Executors.newFixedThreadPool(10);
List<Future<Integer>> futures = new ArrayList<>();
for (int i = 0; i < 10; i++) {
int start = i * 10000;
int end = (i + 1) * 10000;
Future<Integer> future = executorService.submit(new SearchTask(list, start, end, 5000));
futures.add(future);
}
int result = 0;
for (Future<Integer> future : futures) {
result += future.get();
}
System.out.println("Result: " + result);
executorService.shutdown();
}
static class SearchTask implements Callable<Integer> {
private List<Integer> list;
private int start;
private int end;
private int target;
public SearchTask(List<Integer> list, int start, int end, int target) {
this.list = list;
this.start = start;
this.end = end;
this.target = target;
}
@Override
public Integer call() throws Exception {
int count = 0;
for (int i = start; i < end; i++) {
if (list.get(i) == target) {
count++;
}
}
return count;
}
}
}
```
上述代码中,我们首先创建了一个包含100000个整数的List,然后创建了一个包含10个线程的线程池。接着,我们将List分成10个部分,每个线程负责查询其中一个部分。每个线程查询完成后,将查询结果返回给主线程,主线程将所有结果相加得到最终结果。这样,我们就实现了多线程查询List的功能。