06.20 如何學習多線程作加法計算

問題:多線程計算1+2+…+100,如:起四個線程,分別計算1+2+..25, 26+27+…+50, 51+52+…+75, 76+77+…100, 最後將總和相關,輸出應為5050

解決方法:

  • 依次調用thread.join(),主線程輸出結果。注意:sum為共享變量,訪問共享變量時,用synchronized同步
  • 使用countDownLatch, 子線程執行完調用 countdownlatch.countdown(),主線程調用countdownlatc.await() 等待子線程執行完成,輸出結果。 注意:sum為共享變量,訪問共享變量時,用synchronized同步
  • 使用cyclicbarrier, 子線程執行完調用 cyclicbarrier.await(), 最後都到達barrier時,輸出結果。注意:sum為共享變量,訪問共享變量時,用synchronized同步
  • 通過線程池管理線程,用Future取得各子線程執行結果,最後將結果相加。

使用thread.join

依次調用thread.join(),主線程輸出結果。注意:sum為共享變量,訪問共享變量時,用synchronized同步。代碼如下:

package thread;

public class ThreadAdd {
public static int sum = 0;
public static Object LOCK = new Object();


public static void main(String[] args) throws InterruptedException {
ThreadAdd add = new ThreadAdd();
ThreadTest thread1 = add.new ThreadTest(1, 25);

ThreadTest thread2 = add.new ThreadTest(26, 50);
ThreadTest thread3 = add.new ThreadTest(51, 75);
ThreadTest thread4 = add.new ThreadTest(76, 100);
thread1.start();
thread2.start();
thread3.start();
thread4.start();

thread1.join();
thread2.join();
thread3.join();
thread4.join();
System.out.println("total result: "+sum);
}

class ThreadTest extends Thread {
private int begin;
private int end;

@Override
public void run() {
synchronized (LOCK) {
for (int i = begin; i <= end; i++) {
sum += i;
}
System.out.println("from "+Thread.currentThread().getName()+" sum="+sum);
}
}

public ThreadTest(int begin, int end) {
this.begin = begin;
this.end = end;
}
}
}

使用countDownLatch

子線程執行完調用 countdownlatch.countdown(),主線程調用countdownlatc.await() 等待子線程執行完成,輸出結果。 注意:sum為共享變量,訪問共享變量時,用synchronized同步,代碼如下:

package thread;

import java.util.concurrent.CountDownLatch;

public class ThreadAddLatch {
public static int sum = 0;
public static Object LOCK = new Object();
public static CountDownLatch countdown = new CountDownLatch(4);

public static void main(String[] args) throws InterruptedException {
ThreadAddLatch add = new ThreadAddLatch();
ThreadTest thread1 = add.new ThreadTest(1, 25);
ThreadTest thread2 = add.new ThreadTest(26, 50);
ThreadTest thread3 = add.new ThreadTest(51, 75);
ThreadTest thread4 = add.new ThreadTest(76, 100);
thread1.start();
thread2.start();
thread3.start();
thread4.start();

countdown.await();
System.out.println("total result: "+sum);
}

class ThreadTest extends Thread {
private int begin;
private int end;

@Override
public void run() {
synchronized (LOCK) {
for (int i = begin; i <= end; i++) {
sum += i;
}
System.out.println("from "+Thread.currentThread().getName()+" sum="+sum);
}
countdown.countDown();
}

public ThreadTest(int begin, int end) {
this.begin = begin;
this.end = end;
}
}
}


分享到:


相關文章: