Ce este Lock(), UnLock(), ReentrantLock(), TryLock() și cum este diferit de Synchronized Block în Java?]
Publicat: 2020-07-05
În acest tutorial vom trece peste Lock(), UnLock(), ReentrantLock(), TryLock() și cum este diferit de Synchronized Block în Java.
Dacă aveți și întrebări de mai jos, atunci sunteți în locul potrivit.
- Blocări în Java
- Exemplu de blocare Java și blocare simultană vs sincronizat
- Tutorial Java Concurrency – Blocări reentrante
- sincronizare – Utilizarea corectă a blocării/deblocării pentru Java
- java – Sincronizare vs Blocare
- exemplu de deblocare cu blocare java
- mecanism de blocare în java
- java lock debloca diferite fire
Să începem. În primul rând, să înțelegem fiecare dintre acești termeni și apoi vom trece peste exemplu de lucru.
Lacăt():
java.util.concurrent.locks
. O blocare este un mecanism de sincronizare a firelor de execuție precum blocurile sincronizate, cu excepția faptului că blocările pot fi mai sofisticate decât blocurile sincronizate Java. Este o interfață și clase care oferă un cadru pentru blocarea și așteptarea condițiilor care este diferită de sincronizarea și monitoare încorporate.
Deblocare():
UnLock() eliberează blocarea pe Object.
ReentrantLock():
Un ReentrantLock
este deținut de ultimul fir care s-a blocat cu succes, dar nu l-a deblocat încă. Un fir care invocă lock
va reveni, dobândind cu succes blocarea, atunci când blocarea nu este deținută de un alt fir. Metoda va reveni imediat dacă firul curent deține deja blocarea.
TryLock():
TryLock() dobândește blocarea numai dacă este liberă în momentul invocării.
Sfat-1
Dacă pur și simplu blocați un obiect, aș prefera să folosesc synchronized.
1 2 3 |
Lock . lock ( ) ; youMethod ( ) ; // Throws a NullPointerException! Lock . unlock ( ) ; // Here you never release the lock! |
În timp ce cu sincronizarea, este foarte clar și imposibil să greșești:
1 2 3 |
synchronized ( myObject ) { doSomethingNifty ( ) ; } |
Exemplu de detalii:
- Creați clasa: CrunchifyLockTutorial.java
- Creați clase interioare: Company și CrunchifyLoop
- Din Main creați două obiecte din clasa Company
- Începeți bucla de fir pentru 10 pe acele obiecte
- În timp ce Compania1 vorbește cu Compania2 – blochează un obiect. Dacă în același timp – dacă
Company2
dorește să vorbească cuCompany1
, atunci se spune – În conflict – Blocarea există deja. (Ambele companii sunt deja în discuție).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
package crunchify . com . tutorial ; import java . util . Random ; import java . util . concurrent . locks . Lock ; import java . util . concurrent . locks . ReentrantLock ; /** * @author Crunchify.com * */ public class CrunchifyLockTutorial { public static void main ( String [ ] args ) { final Company crunchify = new Company ( "Crunchify" ) ; final Company google = new Company ( "Google" ) ; new Thread ( new CrunchifyLoop ( crunchify , google ) ) . start ( ) ; new Thread ( new CrunchifyLoop ( google , crunchify ) ) . start ( ) ; } // Class CrunchifyLoop static class CrunchifyLoop implements Runnable { private Company companyName1 ; private Company companyName2 ; public CrunchifyLoop ( Company companyName1 , Company companyName2 ) { this . companyName1 = companyName1 ; this . companyName2 = companyName2 ; } public void run ( ) { Random random = new Random ( ) ; // Loop 10 for ( int counter = 0 ; counter < = 10 ; counter ++ ) { try { Thread . sleep ( random . nextInt ( 5 ) ) ; } catch ( InterruptedException e ) { } companyName2 . crunchifyTalking ( companyName1 ) ; } } } // Class Company static class Company { private final String companyName ; // ReentrantLock: Creates an instance of ReentrantLock. This is equivalent to using ReentrantLock(false) private final Lock lock = new ReentrantLock ( ) ; // Constructor public Company ( String name ) { this . companyName = name ; } public String getName ( ) { return this . companyName ; } public boolean isTalking ( Company companyName ) { Boolean crunchifyLock = false ; Boolean googleLock = false ; try { // tryLock: Acquires the lock only if it is free at the time of invocation. crunchifyLock = lock . tryLock ( ) ; googleLock = companyName . lock . tryLock ( ) ; } finally { if ( ! ( crunchifyLock && googleLock)) { if (crunchifyLock) { // unlock: Releases the lock. lock.unlock(); } if ( googleLock ) { companyName . lock . unlock ( ) ; } } } return crunchifyLock && googleLock; } public void crunchifyTalking ( Company companyName ) { // Check if Lock is already exist? if ( isTalking ( companyName ) ) { try { System . out . format ( "I'm %s: talking to %s %n" , this . companyName , companyName . getName ( ) ) ; } finally { lock . unlock ( ) ; companyName . lock . unlock ( ) ; } } else { System . out . format ( "\tLock Situation ==> I'm %s: talking to %s, but it seems" + " we are already talking. Conflicting. %n" , this . companyName , companyName . getName ( ) ) ; } } } } |
Ieșire:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
I 'm Crunchify: talking to Google Lock Situation ==> I' m Google : talking to Crunchify , but it seems we are already talking . Conflicting . I 'm Google: talking to Crunchify I' m Google : talking to Crunchify I 'm Crunchify: talking to Google I' m Google : talking to Crunchify I 'm Google: talking to Crunchify I' m Crunchify : talking to Google Lock Situation == > I 'm Google: talking to Crunchify, but it seems we are already talking. Conflicting. Lock Situation ==> I' m Crunchify : talking to Google , but it seems we are already talking . Conflicting . Lock Situation == > I 'm Google: talking to Crunchify, but it seems we are already talking. Conflicting. I' m Crunchify : talking to Google I 'm Google: talking to Crunchify I' m Google : talking to Crunchify I 'm Crunchify: talking to Google I' m Google : talking to Crunchify Lock Situation == > I 'm Google: talking to Crunchify, but it seems we are already talking. Conflicting. Lock Situation ==> I' m Crunchify : talking to Google , but it seems we are already talking . Conflicting . I 'm Crunchify: talking to Google I' m Crunchify : talking to Google I 'm Crunchify: talking to Google I' m Crunchify : talking to Google |
Sfat-2

Puteți realiza tot ceea ce fac utilitarele din java.util.concurrent
cu primitivele de nivel scăzut, cum ar fi synchronized
, volatile
sau wait
.