Concurrency, Java concurrency

Source: Internet
Author: User
// Testlock. javapackage COM. test. thread; import Java. util. arraylist; import Java. util. list; import Java. util. concurrent. executionexception; import Java. util. concurrent. executorservice; import Java. util. concurrent. executors; import Java. util. concurrent. future; import Java. util. concurrent. timeunit; import Java. util. concurrent. locks. lock; import Java. util. concurrent. locks. reentrantlock; public class testlock {Private Static int CNT = 0; private final int num = CNT ++; Private Static lock = new reentrantlock (); Private testlock () {} Private Static testlock ins = NULL; public static/* synchronized */testlock getinstance () {If (INS = NULL) {// If the lock is declared here, this segment cannot be accessed by multiple threads. Code // Lock = new reentrantlock (); lock. lock (); try {If (INS = NULL) {timeunit. milliseconds. sleep (10); ins = new testlock () ;}} catch (interruptedexception e) {e. printstacktrace ();} finally {lock. unlock () ;}} return INS;} public int getnum () {return num;}/*** @ Param ARGs */public static void main (string [] ARGs) {executorservice SVS = executors. newcachedthreadpool (); List <future <testlock> lstobjs = new arraylist <future <testlock> (); For (INT I = 0; I <10; I ++) {lstobjs. add (SVS. submit (New testlockthread ();} For (Future <testlock> FTL: lstobjs) {try {testlock TL = FTL. get ();} catch (interruptedexception e) {e. printstacktrace ();} catch (executionexception e) {e. printstacktrace () ;}} SVS. shutdown () ;}// testlockthread. javapackage COM. test. thread; import Java. util. concurrent. callable; public class testlockthread implements callable <testlock >{@ overridepublic testlock call () throws exception {testlock TL = testlock. getinstance (); system. out. println ("call:" + TL. getnum (); Return TL ;}}

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.