Thread Advanced Applications-Experience 2-synchronization lock explanation and face test case analysis

Source: Internet
Author: User
Tags thread class

1. Introducing a sync Lock

2. Synchronous Lock Case Analysis

 Packagecom.itcast.family;/** Traditional thread usage and precautions*/ Public classTraditionalthread { Public Static voidMain (string[] args) {//one, thread 1; direct new A thread subclass, let the subclass Run method overwrite the parent class's run ()Thread Thread1 =NewThread () {@Override Public voidrun () { while(true){                    Try{Thread.Sleep (500); } Catch(interruptedexception e) {e.printstacktrace (); }                    //Thread 1 Gets the thread name starting from 0, which is thread1--1:thread-0System.out.println ("Thread1--1:" +Thread.CurrentThread (). GetName ()); //here this represents the thread object, because the direct new is the thread classSystem.out.println ("Thread1--2:" + This. GetName ());        }            }                    };        Thread1.start (); /** Operation Result: * thread1--1:thread-0 thread1--2:thread-0*/                                //second, thread 2; no new subclass, give the thread class A method for constructing a runnable parameterThread thread2 =NewThread (NewRunnable () {@Override Public voidrun () { while(true){                    Try{Thread.Sleep (500); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("Thread2--1:" +Thread.CurrentThread (). GetName ()); /*This can not be used here, this here represents the Runable object, not the thread thread object, * Runable is the code host that the thread runs, so to get the name of the thread is generally used * Thread.CurrentThread (). GetName (); not This.getname ()*///System.out.println ("Thread2--2:" +this.getname ());                }            }                    });        Thread2.start (); /** Operation Result: * thread2--1:thread-1 thread1--1:thread-0 thread1--2:thread-0 
    */                /** What is the difference between the two methods of new threading?         * The first is the new thread object, which is used to override the parent class run () method to meet the requirements; * The second is to implement the thread construction method, the constructor method passes in a runnable parameter, implements its run ().         * * Why do most people use the second method instead of the first? * The second method is more consistent with object-oriented thinking; the second method puts the code running in the thread into a Runnable object, and the solid more embodies the object-oriented thinking; the second method is more common and more natural .*/                        //three, thread 3; The following code uses the Run method in thread, not the Run method in Runnable        /** Reason: * If the Run method that does not overwrite the parent class is dominated by the run method of the parent class, the Run method covered by the subclass is the main if overridden; * Constructor method for parent class go back to the Run method in runnable, so here The runnable will not execute*/        NewThread (NewRunnable () {@Override Public voidrun () { while(true){                    Try{Thread.Sleep (500); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("Thread3--runnable:" +Thread.CurrentThread (). GetName ()); }}}) {@Override Public voidrun () { while(true){                    Try{Thread.Sleep (500); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("Thread3--thread:" +Thread.CurrentThread (). GetName ());    }}}.start (); }            /** Single-threaded faster than multithreading, performance is lower, because the switch between multiple threads also takes time, CPU only one * For example: * 1, make steamed bread, I make steamed bread in a table than at three tables do steamed bread fast; it looks like three tables are producing steamed buns, But you go back and forth between these three tables also takes time; * 2, download something when the download more than one faster, this is not the computer itself accelerated, * But the server gives you the bandwidth of other people, simply say you rob someone else's speed; * 3, from U     On the disk to copy things on the computer, test a folder than the separate test to change the sub-folder under the file faster. */}3. Timer case Analysis and Knowledge point application Packagecom.itcast.family;Importjava.util.Date;ImportJava.util.Timer;ImportJava.util.TimerTask;/** Use of Timers timer*/ Public classTraditionaltimer {//It is declared here because internal classes and methods cannot declare static variables    Private Static intCount = 0;  Public Static voidMain (string[] args) {/** Timer: Timer schedule: Dispatch task: Task*/        /** 1. A simple serial bomb timer, the initial new timer (). Schedule (new TimerTask () {* * * @Override public void run () { System.out.println ("bombing!"); }}, * 6000, 3000); The thread is used to display the sleep time, output a time in seconds while (true) {* SYSTEM.OUT.PRINTLN (new Date ()) in 1 seconds. getseconds ()); try {* Thread.Sleep (1000);         } catch (Interruptedexception e) {* E.printstacktrace ();}} */                        /*           * 2. Create a timer that alternately executes at different intervals, which leads to the following knowledge points * New timer (). Schedule (new TimerTask () {@Override                public void Run () {System.out.println ("bombing!");                                      New Timer (). Schedule (* new TimerTask () {* * @Override public void Run () {* SYSTEM.OUT.PRINTLN ("b                                     Ombing! ");}} * * Internal re-nesting timer running results: bombing! bombing! bombing! * bombing!                                             The This * replaces the timer class with this to put the run result: * bombing!                                  Exception in thread "Timer-0"           * Java.lang.IllegalStateException: * Task already scheduled or * Cancelled * Analysis: There will be a timer can no longer dispatch results, because this is            Anonymous Inner class * can only be executed once, cannot loop execution, 2000);        }}, 6000, 3000);            The thread is used to display the sleep time, and output a time in seconds while (true) {System.out.println (New Date ()) in 1 seconds. getseconds ());            try {thread.sleep (1000);            } catch (Interruptedexception e) {e.printstacktrace (); }        }*/                //3. Optimize the alternate execution timer code: for example, a 2-minute explosion, one 4-minute blast, one back.        classMytimertaskextendstimertask{@Override Public voidRun () {count= (count+1)% 2; System.out.println ("Bombing"); NewTimer (). Schedule (NewMytimertask (), 2000+2000*count); }}                NewTimer (). Schedule (NewMytimertask (), 2000);  while(true) {System.out.println (NewDate (). getseconds ()); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); }        }    }}

Thread Advanced Applications-Experience 2-synchronization lock explanation and face test case analysis

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.