multithreading java xync -
i'm new multithreading. need calculate integral partial sums using multiple threads. want find out if threads finished calculating show general sum, i'm doing using sleep(500) it's stupid. how can right way?
public class mainclass { private static int threadcount=10; public static double generalsum=0; private static arraylist<calculatingthread> threads; public static void main(string[] args){ calculator.seta(0); calculator.setb(2); calculator.setn(500); threads=new arraylist<calculatingthread>(); int div=500/threadcount; (int i=0; i<div;i++){ calculatingthread thread=new calculatingthread(); thread.setjk(i*10,(i+1)*10-1); thread.start(); threads.add(thread); } seek { thread.currentthread().sleep(500); system.out.println(generalsum); } grab (interruptedexception e) { e.printstacktrace(); } } } public class calculatingthread extends thread { private int j; private int k; @override public void run(){ system.out.println("partial sum: " + calculator.calcintegral(j, k)); calculator.addtosumm(calculator.calcintegral(j, k)); //this.notify(); } public void setjk(int j,int k) { this.j = j; this.k=k; } } public class calculator { private static double a; private static double b; private static int n; private static double infunction(double x){ homecoming math.sin(x); } private double sum=0; public static void seta(double a) { calculator.a = a; } public static void setb(double b) { calculator.b = b; } public static void setn(int n) { calculator.n = n; } public static double calcintegral(int j,int k) { double result, h; int i; h = (b-a)/n; //Шаг сетки result = 0; for(i=j; <= k; i++) { result += infunction(a + h * - h/2); //Вычисляем в средней точке и добавляем в сумму } result *= h; homecoming result; } public static synchronized void addtosumm(double sum){ mainclass.generalsum+=sum; } }
p.s. sorry, know code stupid, refactor later
replace
thread.currentthread().sleep(500);
with
for (thread thread : threads) { thread.join(); }
this create main thread wait until created threads completed. can refer wait until threads finish work in java
java multithreading
No comments:
Post a Comment