gpt4 book ai didi

java - 如何使用多线程查找数字范围的总和?

转载 作者:行者123 更新时间:2023-11-29 04:06:43 24 4
gpt4 key购买 nike

系统应该计算一个数字范围内的 x 个线程数的总和,其中数字范围和 x 个线程数由用户输入。

如果要在 2 个线程中计算范围是 1-4 的示例:

Thread 1: 1 + 2 = 3
Thread 2: 3 + 4 = 7

Total = 10

MyThread 类只是我为更好地理解线程的工作原理而编写的示例,而不是解决方案的实际尝试。

我的线程类:

class MyThread implements Runnable {
private String name;

MyThread(String thread) {
name = thread;
System.out.println("Start: " + name);
try { Thread.sleep(500); } catch (Exception e) { System.out.println(e); }
}

//countdown from 5 to 1 for each thread
@Override
public void run() {
for (int i=5; i>0; i--){
System.out.println(name + ": " + i);
try { Thread.sleep(500); } catch (Exception e) { System.out.println(e); }
}
System.out.println(name + " Exiting");
}
}

主类:

public class SimpleThreadExample {
public static void main (String[] args) throws InterruptedException {
Thread t = new Thread();

//get number of threads from user
System.out.print("Enter the number of threads: ");
Scanner input = new Scanner(System.in);
int number = input.nextInt();

//create the threads
for (int i=1; i<=number; i++) {
t = new Thread(new MyThread("Thread " + i));
t.start();
}

t.join();
System.out.println("End");
}
}

我目前不知道应该如何在不同的线程中显示和添加数字。任何建议将不胜感激。

最佳答案

一种简单的 Java-8 方法是使用并行流。

int[] numbers = {1,2,3,4,5,6,7,8,9,10};

int sum = Arrays.stream (numbers).parallel()
.sum ();

如果您需要通过手动创建线程来完成。您可以围绕以下几行做一些事情。

    CountDownLatch countDownLatch = new CountDownLatch (2);

SummationTask task1 = new SummationTask (countDownLatch,Arrays.copyOfRange (numbers, 0, numbers.length / 2));
SummationTask task2 = new SummationTask (countDownLatch,Arrays.copyOfRange (numbers, (numbers.length / 2), numbers.length));
Thread thread = new Thread (task1);
Thread thread2 = new Thread (task2);
thread.start ();
thread2.start ();
try {
countDownLatch.await ();
int totalSum = task1.sum + task2.sum;
System.out.println ("sum => " + totalSum);
} catch (InterruptedException e) {
e.printStackTrace ();
}

在 SummationTask 中,添加拆分数组元素。

class SummationTask implements Runnable {

CountDownLatch countDownLatch;
int[] arr;
int sum;

public SummationTask(CountDownLatch countDownLatch, int[] arr) {
this.countDownLatch = countDownLatch;
this.arr = arr;
}

@Override
public void run() {
int sum = Arrays.stream (arr)
.sum ();
this.sum = sum;
countDownLatch.countDown ();
}
}

PS:上面的解决方案创建了 2 个线程,您可以通过使用所需大小的 ThreadPool(按间隔拆分数组)以及 CallableFuture 来改进它.如果您使用 Future

,则可以摆脱 CountDownLatch

关于java - 如何使用多线程查找数字范围的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58143347/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com