mirror of
https://github.com/Dichgrem/Java.git
synced 2025-12-18 13:21:59 -05:00
update:demo6
This commit is contained in:
52
com/study/demo6/SumThread.java
Normal file
52
com/study/demo6/SumThread.java
Normal file
@@ -0,0 +1,52 @@
|
||||
package com.study.demo6;
|
||||
|
||||
public class SumThread {
|
||||
static class PartSumTask implements Runnable {
|
||||
private final int[] array;
|
||||
private final int start;
|
||||
private final int end;
|
||||
public long result;
|
||||
|
||||
public PartSumTask(int[] array, int start, int end) {
|
||||
this.array = array;
|
||||
this.start = start;
|
||||
this.end = end;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
long sum = 0;
|
||||
for (int i = start; i <= end; i++) {
|
||||
sum += array[i];
|
||||
}
|
||||
result = sum;
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
int size = 1_000_000;
|
||||
int[] array = new int[size];
|
||||
for (int i = 0; i < size; i++) {
|
||||
array[i] = i;
|
||||
}
|
||||
|
||||
PartSumTask task1 = new PartSumTask(array, 0, 333_333);
|
||||
PartSumTask task2 = new PartSumTask(array, 333_334, 666_666);
|
||||
PartSumTask task3 = new PartSumTask(array, 666_667, 999_999);
|
||||
|
||||
Thread t1 = new Thread(task1);
|
||||
Thread t2 = new Thread(task2);
|
||||
Thread t3 = new Thread(task3);
|
||||
|
||||
t1.start();
|
||||
t2.start();
|
||||
t3.start();
|
||||
|
||||
t1.join();
|
||||
t2.join();
|
||||
t3.join();
|
||||
|
||||
long total = task1.result + task2.result + task3.result;
|
||||
System.out.println("总和为:" + total);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user