JAVA Simulation instantly high concurrency

Source: Internet
Author: User

A few days ago received an interview phone, interview content I was very impressed, how to simulate a concurrency? My answer was correct, but I felt a lack of practical details and a general description.

My answer was: "All threads wait at the same node and then notifyall on a node." ”

Interviewer: "Have you heard of the surprise group effect?" ”

Me: "I've never heard of this noun, but I know that waking up all the threads in an instant will make the CPU load instantly increase." ”

Interviewer: "Do you have any way to improve it?" ”

Me: "Using blocking technology, in a node to block all the threads, the use of conditions, the number of threads reached a certain number of times, open blocking." ”

The interviewer seemed to be quite satisfied and ended the topic.

At the end of the interview, I looked back at the block and thought about how to block it. My first idea is to use Atointeger to calculate the number of threads, then use the Synchronize method block to block a thread, according to Atointeger's judgment, the execution of sleep.

The code is as follows:

/** * Created with IntelliJ idea. * User: Rookie daming  * date:14-10-21 * time: PM 4:34 * to change this T Emplate Use File | Settings | File Templates. */public class CountDownLatchTest1 implements runnable{    final Atomicinteger Number = new Atomicinteger ();    volatile Boolean bol = false;    @Override   & nbsp public void Run () {        System.out.println (Number.getandincrement ());         synchronized (this) {             try {                if (! BOL) {                     System.out.println (BOL);                     Bol = True;                     Thread.Sleep (10000);                }           } catch (Interruptedexception e) {                 e.printstacktrace ();            }             System.out.println ("Concurrent quantity is" + Number.intvalue ());       }    }    public static void Main (string[] args) {         Executorservice pool = executors. Newcachedthreadpool ();        CountDownLatchTest1 test = new CountDownLatchTest1 ();        for (int i=0;i<10;i++) {            pool.execute (test);        }   }}
The result is:

02143false56789 Concurrent quantity is 10 concurrent quantity is 10 concurrent quantity is 10 concurrent quantity is 10 concurrent quantity is 10 concurrent quantity is 10 concurrent quantity is 10 concurrent quantity is 10 concurrent quantity is 10 concurrent quantity is 10

From the results, it should be possible to solve the problem, the use of synchronous lock, volatile solve the problem of simultaneous release, the difficulty lies in the switch.

Later looking for information, found a Countdownlatch class, specifically to do this

Countdownlatch is a synchronous helper class, like a countdown counter, when you create an object by constructing a method to set the initial value, call the Countdownlatch object's await () method is in the wait state, call the countdown () method to reduce the counter by 1, When the count arrives at 0 o'clock, all the waiting or a single person waits for execution to begin.

The constructor method parameter specifies the number of times the count

New Countdownlatch (1)

Countdown method, the current thread calls this method, then the count is reduced by one

Cdanswer.countdown ();

Awaint method, calling this method will block the current thread until the value of the timer is 0

Cdorder.await ();

Direct sticker code, reprint of the Code

/** * * @author administrator * The program is used to simulate sending commands and executing commands, the main thread represents the commander, the new 3 threads represent the warrior, the warrior waits for the commander to give orders,  * If the commander does not give orders, the soldiers must wait. Once the orders were issued, the soldiers went to perform their tasks, the commanders were waiting, the soldiers were reported to  * commander, and the commanders ended the waiting.  */public class countdownlatchtest {    public static void Main (string[] args) {   & nbsp;    Executorservice service = Executors.newcachedthreadpool (); Create a thread pool         final Countdownlatch cdorder = new Countdownlatch (1);//Commander's orders, Set to 1, when the Commander orders, the Cutdown, turns 0, the soldiers perform tasks         final Countdownlatch cdanswer = new Countdownlatch (3);//Because there are three warriors, so the initial value is 3, each warrior performs a task Cutdown once, when three are executed and become 0, the commander stops waiting.         for (int i=0;i<3;i++) {             Runnable Runnable = new Runnable () {                 public void Run () {                    Try {                          System.out.println ("Threads" + thread.currentthread (). GetName () +                                  "Ready to accept command");                         cdorder.await (); The soldiers are waiting. Command status                          System.out.println ("Threads" + thread.currentthread (). GetName () +                                  "accepted command");                         Thread.Sleep ((Long) ( Math.random () *10000));                         System.out.println ("Threads" + thread.currentthread (). GetName () +                                 "Responding to Command processing results");                    } catch ( Exception e) {                         e.printstacktrace ();                     finally {                         Cdanswer.countdown () ; The mission was completed and returned to the commander, Cdanswer minus 1.                     }               }            };             Service.execute (runnable);//Add tasks to the thread pool        }         try {            thread.sleep (( Long) (Math.random () *10000));            SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () +&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp;            "upcoming Commands");             Cdorder.countdown (); Send command, Cdorder minus 1, waiting for the soldiers to stop waiting to go to perform their task.             System.out.println ("Threads" + thread.currentthread (). GetName () +                     "sent command, waiting for results");            Cdanswer.await (); Command sent after the commander is in a wait state, once the cdanswer is 0 o'clock stop waiting to continue execution             SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () +                     "received all response results");         catch (Exception e) {            E.printstacktrace ();        } finally {       }         Service.shutdown (); End of task, stop all threads of thread pool    }}
Execution Result:

Thread Pool-1-thread-2 is preparing to accept the command thread pool-1-thread-3 is preparing to accept the command thread pool-1-thread-1 is preparing to accept the command thread, main is about to publish the command thread Pool-1-thread-2 has accepted the command thread Pool-1-thread -3 has accepted the command thread Pool-1-thread-1 has accepted the command thread, main has sent the command, Waiting for result thread pool-1-thread-2 response command processing result thread pool-1-thread-1 response command processing result thread pool-1-thread-3 response command processing result thread main has received all response results

The above is also a way of implementation, with the Countdownlatch await () method, instead of the Synchronize and sleep blocking function, through the countdown method as a switch, and calculate the number of threads a way.

As for the difference in performance, I still don't have a chance to test it at the moment.


JAVA simulation Instant high concurrency

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.