A good solution in multithreading is the producer consumer mode!
In the producer consumer mode, there are usually two types of threads, namely many producer threads and many consumer threads. The production thread is responsible for submitting user requests, and the consumer thread is responsible for processing the tasks submitted by the producer; however, the producer does not know the existence or need of the consumer, because there is a buffer zone between the consumer and the producer, which serves as a bridge between the producer and the consumer, because of the existence of this cache area, there is a time difference between producers and consumers in the execution speed. Whether the speed of a producer in a certain sentence is higher than that of the consumer, or the consumer is higher than that of the producer at a certain time, this buffer zone plays an important role.
Private volatile boolean isRuning = false;
// Memory cache area
Private BlockingQueue BlockQueue;
// Total number of atomic operations
Private static AtomicInteger count = new AtomicInteger ();
// Wait time
Private static final int SLEEPTIME = 1000;
// Constructor
Public Product (BlockingQueue Queue ){
This. blockQueue = queue;
}
@ Override
Public void run (){
PCData data = null;
Random r = new Random ();
System. out. println ("start producer id =" + Thread. currentThread (). getId ());
While (isRuning ){
Try {
Thread. sleep (r. nextInt (SLEEPTIME ));
// Number of constructed tasks
Data = new PCData (count. incrementAndGet ());
If (! BlockQueue. offer (data, 20, TimeUnit. SECONDS )){
System. out. println ("failed to submit data !!!!!! ");
}
} Catch (InterruptedException e ){
E. printStackTrace ();
Thread. currentThread (). interrupt ();
}
}
}
Public void stop (){
IsRuning = false;
}
Public class Customer implements Runnable {
// Buffer zone
Private BlockingQueue CustomerQueue;
Private static final int SLEEPTIME = 1000;
Public Customer (BlockingQueue CustomerQueue ){
This. customerQueue = customerQueue;
}
@ Override
Public void run (){
System. out. println ("Customer id is:" + Thread. currentThread (). getId ());
Random random = new Random ();
While (true ){
PCData data;
Try {
Data = customerQueue. take ();
If (data! = Null ){
Int re = data. getIntData ();
Re = (int) Math. pow (re, 2 );
System. out. println (MessageFormat. format ("{0} * {1} = {2}", data. getIntData (), data. getIntData (), re ));
Thread. sleep (random. nextInt (SLEEPTIME ));
}
} Catch (InterruptedException e ){
E. printStackTrace ();
Thread. currentThread (). interrupt ();
}
}
}
}