import java.util.concurrent.executorservice;import java.util.concurrent.executors;/** * created by alpha on 14-8-15. */public class main { private static final int TIMES = 100 * 1000 * 1000; public static void main (String[] args) throws Exception { ExecutorService service = Executors.newfixedthreadpool (Runtime.getruntime (). Availableprocessors ()); long t1 = system.currenttimemillis (); for (int i=0;i<times;i++) { service.submit (() -> {}); } Service.shutdown (); long t2 = System.currenttimemillis (); system.out.printf ("elapsed Time: %.3fs\n ", (T2-T1)/1000f); }}
Execution Result:
$ time Java-server-jar Run.jar cpus:2elapsed time:351.792sreal6m8.410suser8m50.828ssys0m8.616s
Go language:
When initialized, it looks like it will start 4 goroutine, according to this feature, judging when Goroutine < 4 o'clock, the main thread exits. (It may be possible to start different numbers of goroutine depending on the system, or the four goroutine are required for the system to be used.) So before the test, judge how many Goroutine started)
The package Mainimport ("Runtime" "FMT" "Time") is const (Times = ~ + *) and func main () {runtime. Gomaxprocs (runtime. NUMCPU ()) fmt. Println ("CPUs:", runtime.) NUMCPU (), "Goroutines:", runtime. Numgoroutine ()) T1: = time. Now () for i:=0; i<times; i++ {go func () {} ()}for runtime. Numgoroutine () > 4 {//fmt. Println ("Current Goroutines:", runtime.) Numgoroutine ())//time. Sleep (time. Second)}t2: = time. Now () Fmt. Printf ("Elapsed time:%.3fs\n", T2. Sub (T1). Seconds ())}
Execution Result:
$ time./threadcpus:2elapsed Time:71.974sreal1m12.004suser1m33.765ssys 0m3.418s
Machine configuration: Intel (R) Core (TM) 2 Duo CPU T5870 @ 2.00GHz, memory 8G.
Because Java multithreading mechanism and Golang goroutine mechanism is not the same, from this test can be seen, when the system occurs 100 million times concurrency, Java Multi-threaded context switch occupies a lot of time, takes up a lot of CPU time, the system load is high. Goroutine executes 100 million times concurrently, under the same threading condition, the processing speed is 4 times times the Java Multi-threading. Since the Golong is started, it will be based on runtime. Gomaxprocs sets concurrent threads, 100 million goroutine will run between these two threads. High efficiency.