Recently looking at "Java Virtual machine concurrency Programming", here to record some important stuff.
Determine the number of threads:
1. Get the number of processor cores available on the system: int numofcores = Runtime.getruntime (). Availableprocessors ()
2. If the task is computationally intensive, the number of threads = Numofcores
If the task is IO-intensive, the number of threads = numofcores/(1-blocking factor), where the blocking factor is between 0~1.
Note: If the task is blocked longer than the execution time, these tasks are IO intensive and we need to create a thread that is several times larger than the number of processor cores
It is much more affordable to keep the processor busy in the process of resolving the problem than to divide the load into each sub-task.
Task completion does not mean that the thread dies.
Compute-intensive tasks: If you ask for the number of all primes in 1 to 10000000
1. Abstractprimefinder
Public Abstract classAbstractprimefinder { Public BooleanIsPrime (Final intNumber ) { if(number <= 1)return false; for(inti = 2; I <=math.sqrt (number); i++){ if(number% i = = 0) return false; } return true; } Public intCountprimesinrange (Final intLowerFinal intUpper) { intTotal = 0; for(inti = lower; I <= Upper; i++){ if(IsPrime (i)) total++; } returnTotal ; } Public voidTimeandcomputer (Final intNumber ) { LongStart =System.nanotime (); intNumberofprimes =countprimes (number); LongEnd =System.nanotime (); System.out.printf ("Number of primes under%d is%d\n", number, numberofprimes); System.out.println ("Spend time (seconds) is" + (End-start)/1.0e9); } Public Abstract intCountPrimes (Final intNumber );}
2. Concurrentprimefinder
/*** For computationally intensive tasks, increasing the number of threads does not make sense, and the number of threads should be equal to the number of CPU cores. If the task is more difficult to share to the CPU, then * can be divided into more chunks of the task, to ensure that the CPU completed a certain task, can continue to process other blocks. Prevents a CPU from being idle after completing a task. * @authorSHJ **/ Public classConcurrentprimefinderextendsabstractprimefinder{Private Final intpoolsize; Private Final intNumberofparts; PublicConcurrentprimefinder (intPoolsize,intnumberofparts) { This. poolsize =poolsize; This. Numberofparts =Numberofparts; } @Override Public intCountPrimes (Final intNumber ) { intCount = 0 ; Try{List<Callable<Integer>> partitions =NewArraylist<>(); intChunksperpartition = number/Numberofparts; for(inti = 0; i < numberofparts; i++){ Final intLower = (I * chunksperpartition) + 1; Final intUpper = (i = = numberOfParts-1)? Number:lower + chunksPerPartition-1; Partitions.add (NewCallable<integer>(){ PublicInteger Call () {returnCountprimesinrange (lower, upper); } }); } executorservice Executorpool=Executors.newfixedthreadpool (poolsize); List<Future<Integer>> results = executorpool.invokeall (partitions, 10000, Timeunit.seconds); Executorpool.shutdown (); for(future<integer>result:results) {Count+=Result.get (); } }Catch(Exception e) {e.printstacktrace (); } returncount; } Public Static voidMain (string[] args) {intCores =runtime.getruntime (). Availableprocessors (); intNumberofparts = 20;//Divide the number of sub-intervals, modify this value to see the change in elapsed time NewConcurrentprimefinder (cores,numberofparts). Timeandcomputer (10_000_000); }}
Java Multithreaded Learning Notes (i)--compute-intensive tasks