Package cn.java.core.ch03.job.job03;
Import Java.util.Scanner;
public class MultiCalc {
Private long startTime = 0L;
Private long EndTime =0l;
Private long totalresult = 0L;
Private boolean[] iscompleted = null;
public static void Main (string[] args) {
(New MultiCalc ()). StartUp ();
}
Private Boolean issuccessed () {
for (int i=0;i<iscompleted.length;i++) {
if (!iscompleted[i])
return false;
}
return true;
}
private void StartUp () {
int threadnum;
Long numbers = 100L;
System.out.println ("Please enter the number of threads to open");
Scanner input = new Scanner (system.in);
Threadnum = Input.nextint ();
iscompleted = new Boolean[threadnum];
System.out.println ("Start timing ....");
StartTime = System.currenttimemillis ();
for (int i=1;i<=threadnum;i++) {
Iscompleted[i-1] =false;
Thread t = new Thread (new Calcthread (I,numbers,threadnum));
T.start ();
}
Synchronized (multicalc.this) {
try {
MultiCalc.this.wait ();
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
EndTime = System.currenttimemillis ();
SYSTEM.OUT.PRINTLN ("The result of the calculation is:" +totalresult);
SYSTEM.OUT.PRINTLN ("Timing is over, the total time is:" + (Endtime-starttime) + "MS");
}
Class Calcthread implements runnable{
Private long start;
private long end;
private long result;
private int threadindex;
Public calcthread (int threadindex,long numbers,int threadnum) {
Long step = Numbers/threadnum;
This.threadindex = Threadindex;
Start = (threadIndex-1) *step+1;
if (threadindex==threadnum) {//is the last thread
end = numbers;
}else{
end = Threadindex*step;
}
System.out.println (Thread.CurrentThread (). GetName () +
"---->" +start+ "~" +end);
}
@Override
public void Run () {
for (long i=start;i<=end;i++) {
try {
Thread.Sleep (10);
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
Result+=i;
}
SYSTEM.OUT.PRINTLN (result);
Synchronized (multicalc.this) {
Totalresult +=result;
Iscompleted[this.threadindex-1] = true;
if (issuccessed ()) {
MultiCalc.this.notify ();
}
}
System.out.println (Totalresult);
}
}
}
Multithreading is used to calculate the cumulative number of numbers between 1 and 1000000000 and to compare how much time is spent on multiple threads