public class Main { public static void main(String[] args) throws InterruptedException { Thread[] threads = new Thread[10]; for (int i = 0; i < 10; i++) { final int start = i * 10 + 1; threads[i] = new Thread(() -> { int sum = 0; for (int j = start; j <= start + 9; j++) { sum += j; } System.out.println(Thread.currentThread().getName() + "计算结果为:" + sum); }); threads[i].start(); } int totalSum = 0; for (int i = 0; i < 10; i++) { threads[i].join(); totalSum += threads[i].getResult(); } System.out.println("总结果为:" + totalSum); } }getResult()方法怎么在MyThread类中自定义
时间: 2024-01-21 15:02:50 浏览: 23
在MyThread类中自定义getResult()方法需要先在MyThread类中定义一个int类型的变量result,然后在run()方法中计算出当前线程的结果并赋值给result变量。最后在getResult()方法中返回result变量即可。
示例代码如下:
```
public class MyThread extends Thread {
private int start;
private int result;
public MyThread(int start) {
this.start = start;
}
@Override
public void run() {
int sum = 0;
for (int i = start; i <= start + 9; i++) {
sum += i;
}
result = sum;
System.out.println(Thread.currentThread().getName() + "计算结果为:" + sum);
}
public int getResult() {
return result;
}
}
```
在Main类中使用MyThread类时,需要将threads数组中的元素类型改为MyThread,并修改getResult()方法的调用方式,示例代码如下:
```
public class Main {
public static void main(String[] args) throws InterruptedException {
MyThread[] threads = new MyThread[10];
for (int i = 0; i < 10; i++) {
final int start = i * 10 + 1;
threads[i] = new MyThread(start);
threads[i].start();
}
int totalSum = 0;
for (int i = 0; i < 10; i++) {
threads[i].join();
totalSum += threads[i].getResult();
}
System.out.println("总结果为:" + totalSum);
}
}
```