Java concurrency is a very common point of knowledge. Interview is basically a must ask, work is also commonly used.
Concurrent risk: 1, program hunger, such as a program to run the time to get the operator's confirmation, but the operator to eat, the program will always be in the waiting state. 2, Deadlock: Wait for each other's resources. 3, resource competition: two programs compete for the same resources. Give me a chestnut: Calculate the number of primes in a range, first, in the usual order, and then use multithreading to compute. Compare the execution efficiency of both. Here is a tool class, which is used for both sequential and multithreaded computations.
Package com.sunyard.demo.concurrency; /** * This class is used as a tool class/public abstract class Abstractprimefinder {/** * To determine whether a number is prime * @param # * @retu
RN/Public boolean isprime (final int number) {if (number <= 1) return false;
for (int i=2;i<=math.sqrt (number), i++) if (number% i==0) return false;
return true; /** * Calculates the number of primes in an interval * @param lower * @param Upper * @return/public int Countprimesi
Nrange (final int lower,final int upper) {int total=0;
for (int i=lower;i<=upper;i++) if (IsPrime (i)) total++;
return total; /** * Statistics program time spent calculating prime numbers * @param number/public void Timeandcompute (final int number) {fi
nal Long start = System.nanotime ();
Final long numberofprimes=countprimes (number);
Final Long end = System.nanotime (); System.out.printf ("Number of primes under%d is%d\n", Number,numbeRofprimes);
System.out.println (seconds) taken is: "+ (End-start)/1.0e9);
public abstract int CountPrimes (final int number);
}The single thread is as follows:
Package com.sunyard.demo.concurrency;
/**
* Start class/public
class Sequentialprimefinder extends Abstractprimefinder {
/**
* Implement methods
in the parent class * @param number
* @return * *
@Override public
int countprimes (final int number) {
return Countprimesinrange (1,number);
}
/**
* Program Main method
* @param args
/public static void main (string[] args) {
//calculated interval 1 to 10000000
new Sequentialprimefinder (). Timeandcompute (10000000);
}
}
Multithreading is as follows:
public class Concurrentprimefinder extends Abstractprimefinder {private final int poolsize;//number of threads created by private FINA
l int numberofparts;//Task number/** * Construction method initializes the number of threads and the division of tasks * @param poolsize * @param numberofparts * *
Public Concurrentprimefinder (final int poolsize, final int numberofparts) {this.poolsize = poolsize;
This.numberofparts = Numberofparts;
@Override public int countprimes (final int number) {int count=0;//counts the number of numbers in each interval try {
Final list<callable<integer>> partitions=new arraylist<callable<integer>> ();
final int chunksperpartion=number/numberofparts;
for (int i=0; i<numberofparts;i++) {final int lower= (i*chunksperpartion) +1; Final int upper= (i==numberofparts-1)?
number:lower+chunksperpartion-1; Partitions.add (New callable<integer> () {@Override PUBlic Integer Call () {return countprimesinrange (lower,upper);
}
}); Final Executorservice executorpool= Executors.newfixedthreadpool (poolsize)//thread pool Create threads final Lis
T<future<integer>> Resultfromparts=executorpool.invokeall (partitions,10000,timeunit.seconds);
Executorpool.shutdown ()///After completion, close the thread pool for (final future<integer> result:resultfromparts)//Count the number of primes for each task
Count +=result.get ();
}catch (Exception ex) {throw new RuntimeException (ex);
return count;
public static void Main (string[] args) {new Concurrentprimefinder (4,4). Timeandcompute (10000000); }
}