In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/03 Report--
Sometimes it is most convenient to write a simple demo to simulate a concurrent request if you want to test the concurrency ability of a function without the help of other testing tools. If you are familiar with jemter testing the concurrency capability of an interface is actually more professional, you are just messing around.
CountDownLatch and CyclicBarrier are two very useful concurrency utility classes under the jdk concurrent package, which provide a means to control the concurrency process. In fact, looking at the source code, they all maintain a counter control flow internally.
CountDownLatch: one or more threads waiting for other threads to finish something before they can execute.
CyclicBarrier: multiple threads wait for each other until they reach the same synchronization point, and then continue to execute together.
The difference between CountDownLatch and CyclicBarrier
The counter of CountDownLatch. The thread completes one record at a time. The counter is a decreasing counter and can only be used once.
CyclicBarrier counter is more like a valve, need all threads to arrive before the valve can be opened, and then continue to execute, the counter is an incremental counter to provide reset function, can be used multiple times
In addition, Semaphore can control the number of threads accessed at the same time, obtain a license through acquire (), wait if not, and release () releases a license.
Usually we simulate concurrent requests, usually open a few more threads, and just initiate the request. But the way, generally there will be a start-up sequence, it is not really concurrent at the same time! How can we achieve real simultaneous concurrency? The point of this article is that locking CountDownLatch is provided in java, and CyclicBarrier is most appropriate for doing this kind of thing.
The following uses CountDownLatch and CyclicBarrier to simulate concurrent requests, respectively
CountDownLatch simulation
Package com.test
Import java.io.BufferedReader
Import java.io.IOException
Import java.io.InputStream
Import java.io.InputStreamReader
Import java.io.OutputStream
Import java.net.HttpURLConnection
Import java.net.MalformedURLException
Import java.net.URL
Import java.util.concurrent.CountDownLatch
Public class LatchTest {
Public static void main (String [] args) throws InterruptedException {Runnable taskTemp = new Runnable () {
/ / Note that this is not thread-safe. Leave the hole.
Private int iCounter
@ Override public void run () {for (int I = 0; I)
< 10; i++) { // 发起请求 // HttpClientOp.doGet("https://www.baidu.com/"); iCounter++; System.out.println(System.nanoTime() + " [" + Thread.currentThread().getName() + "] iCounter = " + iCounter); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }; LatchTest latchTest = new LatchTest(); latchTest.startTaskAllInOnce(5, taskTemp);}public long startTaskAllInOnce(int threadNums, final Runnable task) throws InterruptedException { final CountDownLatch startGate = new CountDownLatch(1); final CountDownLatch endGate = new CountDownLatch(threadNums); for(int i = 0; i < threadNums; i++) { Thread t = new Thread() { public void run() { try { // 使线程在此等待,当开始门打开时,一起涌入门中 startGate.await(); try { task.run(); } finally { // 将结束门减1,减到0时,就可以开启结束门了 endGate.countDown(); } } catch (InterruptedException ie) { ie.printStackTrace(); } } }; t.start(); } long startTime = System.nanoTime(); System.out.println(startTime + " [" + Thread.currentThread() + "] All thread is ready, concurrent going..."); // 因开启门只需一个开关,所以立马就开启开始门 startGate.countDown(); // 等等结束门开启 endGate.await(); long endTime = System.nanoTime(); System.out.println(endTime + " [" + Thread.currentThread() + "] All thread is completed."); return endTime - startTime;} } 执行结果 CyclicBarrier模拟 // 与 闭锁 结构一致 public class LatchTest { public static void main(String[] args) throws InterruptedException { Runnable taskTemp = new Runnable() { private int iCounter; @Override public void run() { // 发起请求 // HttpClientOp.doGet("https://www.baidu.com/"); iCounter++; System.out.println(System.nanoTime() + " [" + Thread.currentThread().getName() + "] iCounter = " + iCounter); } }; LatchTest latchTest = new LatchTest(); // latchTest.startTaskAllInOnce(5, taskTemp); latchTest.startNThreadsByBarrier(5, taskTemp); } public void startNThreadsByBarrier(int threadNums, Runnable finishTask) throws InterruptedException { // 设置栅栏解除时的动作,比如初始化某些值 CyclicBarrier barrier = new CyclicBarrier(threadNums, finishTask); // 启动 n 个线程,与栅栏阀值一致,即当线程准备数达到要求时,栅栏刚好开启,从而达到统一控制效果 for (int i = 0; i < threadNums; i++) { Thread.sleep(100); new Thread(new CounterTask(barrier)).start(); } System.out.println(Thread.currentThread().getName() + " out over...");} } class CounterTask implements Runnable { // 传入栅栏,一般考虑更优雅方式private CyclicBarrier barrier;public CounterTask(final CyclicBarrier barrier) { this.barrier = barrier;}public void run() { System.out.println(Thread.currentThread().getName() + " - " + System.currentTimeMillis() + " is ready..."); try { // 设置栅栏,使在此等待,到达位置的线程达到要求即可开启大门 barrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " - " + System.currentTimeMillis() + " started...");} } 执行结果 并发请求操作流程示意图如下:A door is set here to ensure that all threads can take effect at the same time. However, the simultaneous startup here is only at the language level, and it is not absolutely concurrent at the same time. Specific calls also depend on the number of CPU, the number of threads and the operating system's thread scheduling functions, but we do not need to dwell on these, the focus is to understand the principle!
After all, it is very convenient to use the professional tool jmeter to test concurrency.
Here to provide you with a learning exchange platform, Java technology exchange ┟ 810309655
With 1-5 work experience, in the face of the current popular technology do not know where to start, need to break through the technical bottleneck can be added.
I stayed in the company for a long time and lived comfortably, but I hit a brick wall in the interview when I changed jobs. Those who need to study and change jobs to get a high salary in a short period of time can join the group.
If you have no work experience, but the foundation is very solid, the working mechanism of java, common design ideas, often use java development framework to master proficiency can be added.
Add Java architect advanced communication group to obtain Java engineering, high-performance and distributed, high-performance, simple and simple. High architecture.
Free learning rights for live streaming of advanced practical information about performance tuning, Spring,MyBatis,Netty source code analysis, big data and other knowledge points
It is Daniel flying that makes you take a lot of detours. The group number is: 810309655, Xiaobai do not enter, it is best to have development experience.
Note: add group requirements
1. Those who have work experience and do not know where to start in the face of the current popular technology, those who need to break through the technical bottleneck can be added.
2. After staying in the company for a long time, I had a very comfortable life, but I hit a brick wall in the job-hopping interview. Those who need to study and change jobs to get a high salary in a short period of time can be increased.
3, if there is no work experience, but the foundation is very solid, the working mechanism of java, common design ideas, often use java development framework to master proficiency, can be added.
4. I think I am very good. B, I can meet my general needs. However, the knowledge learned is not systematic, it is difficult to continue to break through in the field of technology can be added.
5. Ali Java Senior Daniel Live explains knowledge points, shares knowledge, combs and summarizes many years of work experience, and takes you to establish your own technical system and technical cognition comprehensively and scientifically!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.