I got an interview call a few days ago. Interview content I was very impressed, how to simulate a concurrency? While my answer was correct, I felt that I lacked the details of what I could actually do, and there was only a descriptive narrative.
My answer was: "Thread all 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 of the threads in an instant can make the CPU load instantly increase."
”
Interviewer: "Do you have any way to improve it?" ”
Me: "Using clogging technology." A node will plug all the threads in the exploit condition. When the number of threads reaches a certain number. Open the blockage.
”
The interviewer seemed to be more comfortable and ended the conversation.
At the end of the interview, I looked back at this piece of thinking. How do you plug it? The first thing I have is a thought. Use Atointeger to compute the number of threads, then use the Synchronize method block to plug a thread and run sleep based on Atointeger inference.
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 able to solve the problem, the use of synchronous lock, volatile to overcome the same time the problem of release, the difficulty lies in the switch.
Later looking for information, found a Countdownlatch class. Who specializes in this?
Countdownlatch is a synchronous helper class, like a countdown counter, when an object is created, the initial value is set by the constructor method, and the await () method that calls the Countdownlatch object is in a wait state. Calling the countdown () method will reduce the counter by 1, and when the count arrives at 0 o'clock, all the waiting or a single waiting person starts to run.
Construction method parameters Specify the number of counts
New Countdownlatch (1)
Countdown method. This method is called by the current thread, and the count is reduced by one
Cdanswer.countdown ();
Awaint method, calling this method will always 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 running commands, the main thread represents the commander. New 3 threads on behalf of the Warrior, the warrior has been waiting for the commander to give orders, and if the commander has not given orders, the soldiers must wait.Once the command is released, the soldiers go to run their own task. The commander is waiting, and the soldiers are reported to Commander * when their mission is complete. The commander ended the wait. */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 order. Set to 1, the Commander gives an order. Then Cutdown, turns 0, Warriors run quests final Countdownlatch cdanswer = new Countdownlatch (3) ;//Because there are three warriors, so the initial value is 3, each soldier runs the task to complete then cutdown once, when three are run complete, becomes 0. The commander stopped waiting. for (int i=0;i<3;i++) { Runnable Runnable = new Runnable () { public void Run () { try { SYSTEM.OUT.PRINTLN ("Thread" + 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 (); Mission completed, return to Commander, Cdanswer minus 1. } } }; Service.execute (runnable);//join task for thread pool } try { thread.sleep (( Long) (Math.random () *10000)); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "upcoming orders"); Cdorder.countdown (); Send command, Cdorder minus 1, waiting for the soldiers to stop waiting to go run the task. System.out.println ("Threads" + thread.currentthread (). GetName () + "sent command, waiting for results"); Cdanswer.await (); After the command is sent, the commander is in a wait state. Once the Cdanswer is 0 o'clock stop waiting to run down System.out.println (" Thread "+ thread.currentthread (). GetName () + "received all response results"); } catch ( Exception e) { e.printstacktrace (); finally { } Service.shutdown (); The task ends. Stop all threads of thread pool }}
Operation 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 advertise 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, replacing the Synchronize and sleep congestion function, through the countdown method as a switch, and calculate the number of threads a way.
Difference, it is certainly the latter will be better, because the first way to rely on sleep (XXX) to block the grasp of the shortest time, too short, may not reach the fixed number of threads will open the switch.
As for the difference in performance, I don't have a chance to test it now.
JAVA Simulation instantly high concurrency