您好,登錄后才能下訂單哦!
怎么在Java中使用線程計算數組和?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
五個線程交替累加計算數組之和,這種方法其實不如單線程直接累加快,因為交替累加需要前一個線程計算的結果。
package test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class FiveThreadCount { private int count=0; private int[] arr={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28}; private int j=0; //定義一個任務,關鍵點所在 private class MyThread extends Thread{ @Override public void run() { super.run(); while(j<arr.length) { synchronized (MyThread.class) { if(j>=arr.length){ return; } count+=arr[j++]; try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()); } } } } //方法一 public void test1(){ for(int i=0;i<5;i++){ new MyThread().start(); } try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(count); } //方法二 public void test2(){ Thread myThread=new MyThread(); for(int i=0;i<5;i++){ new Thread(myThread).start(); } try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(count); } //方法一的線程池實現版 public void test3(){ ExecutorService service=Executors.newCachedThreadPool(); for(int i=0;i<5;i++){ service.execute(new MyThread()); } try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(count); } //方法二的線程池實現版 public void test4(){ ExecutorService service=Executors.newCachedThreadPool(); Thread myThread=new MyThread(); for(int i=0;i<5;i++){ service.execute(myThread); } try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(count); } }
上邊代碼中,用到了sleep方法的原因,sleep(100)是為了讓其他線程有時間執行任務,如果不sleep的話,有可能一個線程就全部執行完了。 最后的sleep(10000)是為了等所有線程執行完后,打印最后的計算結果。
將數組分為5等分,讓每個線程計算自己負責的那份,并發計算,最后匯總結果。這種方式比代碼一速度會快些。因為線程獨立計算,不依賴其他線程的結果。最后幾個線程將總數累加即可。
使用Callable,FutureTask方式,來實現代碼:
package test; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; public class FiveThreadCount2 { private int[] arr={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28}; private int total=0; public void test() throws InterruptedException, ExecutionException{ ExecutorService service=Executors.newFixedThreadPool(5); int length=arr.length; for(int j=0;j<length;j+=(length/5)){ FutureTask<Integer> task; if( (j+(length/5))<length){ task=new FutureTask<Integer>(new MyCallable(arr, j, j+(length/5))); }else{ task=new FutureTask<Integer>(new MyCallable(arr, j, length)); } service.execute(task); total+=task.get(); } service.shutdown(); System.out.println(total); } public class MyCallable implements Callable<Integer>{ int[] arr; int startIndex; int endIndex; public MyCallable(int[] arr,int startIndex,int endIndex){ this.arr=arr; this.startIndex=startIndex; this.endIndex=endIndex; } @Override public Integer call() throws Exception { int sum=0; for(int i=startIndex;i<endIndex;i++){ sum+=arr[i]; } System.out.println(Thread.currentThread().getName()); return sum; } } }
這個方式有一個缺點,看似5個線程異步執行,其實是順序執行,因為 task.get是要等待線程執行完畢才會執行下邊的代碼。所以效率不會高,可能換種寫法可以解決這個問題,這里就不深入研究。
通過java工具類CountDownLatch實現并發計算
package test; import java.util.concurrent.CountDownLatch; public class FiveThreadCount3 { private int[] arr={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28}; private int total=0; public void test() throws InterruptedException{ int length=arr.length; CountDownLatch latch=new CountDownLatch(length%5==0?5:6); System.out.println(length); for(int j=0;j<length;j+=(length/5)){ MyThread task; if( (j+(length/5))<=length){ task=new MyThread(arr, j, j+(length/5), latch); }else{ task=new MyThread(arr, j, length, latch); } new Thread(task).start(); } latch.await(); System.out.println(total); } private class MyThread implements Runnable{ int[] arr; int startIndex; int endIndex; CountDownLatch latch; public MyThread(int[] arr,int startIndex,int endIndex,CountDownLatch latch){ this.arr=arr; this.startIndex=startIndex; this.endIndex=endIndex; this.latch=latch; } @Override public void run() { int sum=0; for(int i=startIndex;i<endIndex;i++){ sum+=arr[i]; } synchronized (MyThread.class) { total+=sum; } System.out.println(Thread.currentThread().getName()); latch.countDown(); } } }
對于CountDownLatch不熟悉的可以搜索下用法。
通過java工具類 CyclicBarrier實現并發計算。
package test; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; public class FiveThreadCount1 { private int[] arr={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28}; private int total=0; public void test() throws InterruptedException, BrokenBarrierException{ int length=arr.length; CyclicBarrier barrier=new CyclicBarrier((length%5==0?5:6)+1); System.out.println(length); for(int j=0;j<length;j+=(length/5)){ MyThread task; if( (j+(length/5))<=length){ task=new MyThread(arr, j, j+(length/5), barrier); }else{ task=new MyThread(arr, j, length, barrier); } new Thread(task).start(); } barrier.await(); System.out.println(total); } private class MyThread implements Runnable{ int[] arr; int startIndex; int endIndex; CyclicBarrier barrier; public MyThread(int[] arr,int startIndex,int endIndex,CyclicBarrier barrier){ this.arr=arr; this.startIndex=startIndex; this.endIndex=endIndex; this.barrier=barrier; } @Override public void run() { int sum=0; for(int i=startIndex;i<endIndex;i++){ sum+=arr[i]; } synchronized (MyThread.class) { total+=sum; } try { System.out.println(Thread.currentThread().getName()); barrier.await(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (BrokenBarrierException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
Java是一門面向對象編程語言,可以編寫桌面應用程序、Web應用程序、分布式系統和嵌入式系統應用程序。
關于怎么在Java中使用線程計算數組和問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。