The following is a sample code for a multithreaded lock mechanism:
1 Packagelock;2 3 ImportJava.util.concurrent.locks.Lock;4 ImportJava.util.concurrent.locks.ReentrantLock;5 6 Public classThreadTest {7 Private intJ;8 PrivateLock lock =NewReentrantlock ();9 Ten Public Static voidMain (string[] args) { OneThreadTest TT =Newthreadtest (); A for(inti=0; i<2; i++){ - NewThread (TT.NewAdder ()). Start (); - NewThread (TT.NewSubtractor ()). Start (); the } - } - - Private classSubtractorImplementsrunnable{ + Public voidrun () { - while(true){ + A Lock.lock (); at - Try{ -System.out.println ("j--=" + j--); -}finally{ - Lock.unlock (); - } in } - } to } + - Private classAdderImplementsrunnable{ the Public voidrun () { * while(true){ $ Panax Notoginseng Lock.lock (); - Try{ theSystem.out.println ("J + +" + j + +); +}finally{ A Lock.unlock (); the } + } - } $ } $}
Java Lock Example