diff --git a/com/study/demo6/SumThread.java b/com/study/demo6/SumThread.java new file mode 100644 index 0000000..115d065 --- /dev/null +++ b/com/study/demo6/SumThread.java @@ -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); + } +} diff --git a/com/study/demo6/ThreadDemo1.java b/com/study/demo6/ThreadDemo1.java new file mode 100644 index 0000000..5a8c1d2 --- /dev/null +++ b/com/study/demo6/ThreadDemo1.java @@ -0,0 +1,20 @@ +package com.study.demo6; + +public class ThreadDemo1 { + static class MyThread extends Thread { + @Override + public void run() { + for (int i = 1; i <= 5; i++) { + System.out.println("当前线程:" + getName() + ",输出次数 " + i); + } + } + } + + public static void main(String[] args) { + MyThread s1 = new MyThread(); + MyThread s2 = new MyThread(); + + s1.start(); + s2.start(); + } +} diff --git a/com/study/demo6/ThreadDemo2.java b/com/study/demo6/ThreadDemo2.java new file mode 100644 index 0000000..19d9c1d --- /dev/null +++ b/com/study/demo6/ThreadDemo2.java @@ -0,0 +1,22 @@ +package com.study.demo6; + +public class ThreadDemo2 { + static class CountTask implements Runnable { + @Override + public void run() { + for (int i = 1; i <= 10; i++) { + System.out.println(Thread.currentThread().getName() + " 计数:" + i); + try { + Thread.sleep(500); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + public static void main(String[] args) { + Thread t = new Thread(new CountTask(), "计数线程"); + t.start(); + } +}