Some small demo of multithreading

Source: Internet
Author: User

One, multiple threads, single lock
 PackageCom.sun.multithread.sync; Public classMyThreadextendsThread {Private intCount = 5; //Synchronized Locking     Public synchronized voidRun () {count--; System.out.println ( This. CurrentThread (). GetName () + "Count =" +count); }         Public Static voidMain (string[] args) {MyThread MyThread=NewMyThread (); Thread T1=NewThread (MyThread, "T1"); Thread T2=NewThread (MyThread, "T2"); Thread T3=NewThread (MyThread, "T3"); Thread T4=NewThread (MyThread, "T4"); Thread T5=NewThread (MyThread, "T5");        T1.start ();        T2.start ();        T3.start ();        T4.start ();    T5.start (); }}
Two, multiple lines multithreading lock
 PackageCom.sun.multithread.sync; Public classmultithread {Private Static intnum = 0; /*** Add synchronized keyword to static method, means lock class class, Class-level lock * keyword synchronized acquired lock is object lock, rather than a piece of code (method) as a lock, * so which thread in the code executes the first synch Ronized method of the keyword, which thread holds the lock of the object to which the method belongs *@paramTag Parameter*/     Public Static synchronized voidprintnum (String tag) {Try {            if(Tag.equals ("a") ) {num= 100; System.out.println ("Tag A, set num over!"); Thread.Sleep (1000); } Else{num= 200; System.out.println ("Tag b, set num over!"); } System.out.println ("Tag" + tag + ", num =" +num); } Catch(interruptedexception e) {e.printstacktrace (); }    }         Public Static voidMain (string[] args) {//two different objects        FinalMultithread M1 =Newmultithread (); Finalmultithread m2 =Newmultithread (); Thread T1=NewThread (NewRunnable () {@Override Public voidrun () {M1.printnum (A);                }        }); Thread T2=NewThread (NewRunnable () {@Override Public voidrun () {M1.printnum ("B");                }        });        T1.start ();    T2.start (); }}

Some small demo of multithreading

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.