Take you to the Java Multi-threaded series "DAO" Multi-threading advantage and using Util.concurrent packet to test the efficiency of multi-core multithreading under single core

Source: Internet
Author: User

java Multithreading "Tao"-The advantages of multithreading and testing the efficiency of multi-core multithreading under single core with concurrent packet 1 Super elder brother's understanding of multithreading 2 Test Code 3 Countdownlatch This synchronous auxiliary class popular Science 4 How to set up a PC as a single core 5 test Results 1 Super elder brother's understanding of multithreadingElder brother's understanding: for multi-threading, is nothing more than a sequence of tasks under the extraction and encapsulation, the original sequence of tasks taken out of the thread class of the Run method, through the thread class Start method execution, for multi-threaded access to common resources, we need to lock, That is, only one thread in the possession of the lock, only to be able to get execution rights, Super Elder brother a think, bad, this if in the case of a single core, there is only one core to carry out the task, you do, get a multi-threaded, you let a computer kernel also constantly switch different threads to perform tasks, this gets locks, release Switching time is not yet sequential execution of high efficiency, so super-brother Guess only in the multi-core conditions can reflect the high efficiency of multi-threading, in the case of single-core if tinker a multi-threading that is eat full of nothing dry ... Here's an experiment to verify the super-brother conjecture. Experiment: Experimental Environment, computer: HP g42,cpu i3-390, memory 4G Super Brother Poor, no money good machine Knowledge Reserve Requirements: Familiar with Java multi-threading, Java Concurrent Basic use of the package 2 Test Code
ImportJava.util.concurrent.CountDownLatch;  Public classTest { Public Static voidMain (string[] args) {intnum = 100000;          Test1 (num);      Test2 (num); }       Private Static voidTest1 (intmax) {          LongT1 =System.currenttimemillis (); intn =method1 (max); Longt2 =System.currenttimemillis (); System.out.println ("Method1:value=" + N + ", time=" + (T2-T1)/1000.0); }       Private Static intMETHOD1 (intmax) {          intnum = 0;  for(inti = 1; I <= Max; i++) {              BooleanFlag =true;  for(intj = 2; J < I-1; J + +) {                  if(i% j = 0) {flag=false;  Break; }              }              if(Flag && i >num) num=i; }          returnnum; }       Private Static voidTest2 (intmax) {          LongT1 =System.currenttimemillis (); intThreadnumber = 10;//Number of Threads        FinalCountdownlatch Countdownlatch =NewCountdownlatch (threadnumber); intStep = max/Threadnumber;  for(inti = 0; I <= Max; i + =Step) {              if(I-step >= 0) {Calc Calc=NewCalc (I-step + 1, I, Countdownlatch); Thread Thread=NewThread (Calc);              Thread.Start (); }          }          Try{countdownlatch.await (); } Catch(interruptedexception e) {e.printstacktrace (); }          Longt2 =System.currenttimemillis (); System.out.println ("Method2:value=" + calc.getval () + ", time=" + (T2-T1)/1000.0); }  }   classCalcImplementsRunnable {Private StaticInteger val = 0; Private intmin; Private intMax; PrivateCountdownlatch CDL;  PublicCalc (intMinintMax, Countdownlatch CDL) {           This. Min =min;  This. Max =Max;  This. CDL =CDL; }        Public Static intGetval () {returnVal; }        Public voidrun () {intnum = 0;  for(inti = min; I <= Max; i++) {              BooleanFlag =true;  for(intj = 2; J < I-1; J + +) {                  if(i% j = 0) {flag=false;  Break; }              }              if(Flag && i >num) num=i; }          synchronized(val) {if(Num >val) Val=num;      } cdl.countdown (); }   }  

For the sequential execution of the statistics task completion time is very simple, before and after the execution of the task pair through the System.currenttimemillis () method to get the time and subtract, but for multi-threaded how to do it, we can not get multithreaded execution of the task by the following code time
 Public Static void Main (string[] args) {    long t1 = system.currenttimemillis ();           Thread1.start ();         Thread2.start ();         Thread3.start ();         Thread4.start ();         Thread5.start ();   long t2 = system.currenttimemillis ();}

Because the time to get is only the main thread execution, for thread thread1,thread2,thread3,thread4,thread5 time we have no statistics, how to solve, Find the answer in the Java.util.concurrent package, we have countdownlatch this thread synchronizes the helper class 3 Countdownlatch This synchronous auxiliary class popular Science

Countdownlatch This class enables a thread to wait for another thread to complete its work before executing, and the count value in the constructor is actually the number of threads that the latch waits for . This value can only be set once, and Countdownlatch does not provide any mechanism to reset the count value . The first interaction with Countdownlatch is the main thread waiting for other threads. The main thread must call the countdownlatch.await () method immediately after starting another thread. This way the main thread will block on this method until other threads have completed their respective tasks. Other n threads must refer to the latching object because they need to notify the Countdownlatch object that they have completed their respective tasks. This notification mechanism is done through the Countdownlatch.countdown () method, and each time this method is called, the count value initialized in the constructor is reduced by 1. So when n threads call this method, the value of Count equals 0, and the main thread can resume its own task by using the await () method.

4 How to set up a PC as a single coreSuper elder brother in pondering this problem, how to get a single-core computer, in today's time to get a eight core is not difficult, find a single core of the difficult ah, can I turn off a core of the dual-core computer, think of Baidu, Haha, really can, first click on the bottom left corner of windows in the search bar input msconfig, Enter the advanced settings for Windows Startup items as we tick the number of processors in the advanced boot options, and select 1 in the dropdown bar, the others do not need to be changed, then restart, say restart, Super elder brother has to talk about the benefits of OSGi architecture, if you want to Java OSGi architecture, only need to change , and do not need to restart the effective, this restart is very, again into Windows when the direct card in the beginning of the screen freezes, successive three times are so, super Brother Panic, the computer to play waste, not afraid, the fourth time when the Super elder brother use the Windows Safe Mode to start, haha success This is going into eclipse, open the test program 5 test ResultsMethod1 represents a time that is not multi-threaded, and METHOD2 represents the time to adopt multithreading 5.1 test results under single-core conditionsWe first set the number of threads to 10 threads to 20 cases where the number of threads is 30, from the above we can see in the case of a single core, using multithreading is slower than sequential execution, each multithreading is more than the sequential execution of a few milliseconds, also confirms the Super elder brother before the conjecture, get lock, release lock don't need time? 5.2 test results under dual-core conditionsThe number of threads is 10 the case of the thread number of 20 of the case of the number of cases of 30 of the case of the two-core case, we can see that the use of multi-threaded operation takes about 50% of the sequential execution time, in today's multi-core era, 4 cores, 8 cores, multi-threaded role can be imagined. So learning multithreading is very necessary in the Super brother take you to play multi-threaded series, Super elder brother will introduce multi-threaded synchronization and scheduling to everyone ...

Take you to the Java Multi-threaded series "DAO" Multi-threading advantages and the use of Util.concurrent packet testing the efficiency of multi-core multithreading under single core

Related Article

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.