Java Multithreading (ii) Synchronized throw exception lock auto release

Source: Internet
Author: User
Tags throw exception

When a thread executes a code exception, the locks it holds are automatically freed

 Public classMyObject {Private inti = 1; synchronized  Public voidMethodA ()throwsinterruptedexception {System.out.println ("Begin MethodA Threadname=" +Thread.CurrentThread (). GetName ()); if(i==1){            Throw Newinterruptedexception (); } System.out.println ("End MethodA"); }    synchronized  Public voidMethodB ()throwsinterruptedexception {System.out.println ("Begin MethodB Threadname=" +Thread.CurrentThread (). GetName ()); System.out.println ("End MethodB"); }}

Threada and THREADB

 Public classThreadaextendsThread {PrivateMyObject MyObject;  PublicThreada (MyObject MyObject) { This. MyObject =MyObject; }     Public voidrun () {Try{Myobject.methoda (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }} Public classThreadbextendsThread {PrivateMyObject MyObject;  Publicthreadb (MyObject MyObject) { This. MyObject =MyObject; }     Public voidrun () {Try{myobject.methodb (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }}
View Code

Run

 Public class Run {    publicstaticvoid  main (string[] args) {        new MyObject ();         New Threada (object);        Threada.setname ("A");        Threada.start ();                 New threadb (object);        Threadb.setname ("B");        Threadb.start ();        }}
View Code

Java Multithreading (ii) Synchronized throw exception lock auto dismiss

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.