Che cos'è Lock(), UnLock(), ReentrantLock(), TryLock() e come è diverso da Synchronized Block in Java?]
Pubblicato: 2020-07-05
In questo tutorial esamineremo Lock(), UnLock(), ReentrantLock(), TryLock() e come è diverso da Synchronized Block in Java.
Se hai anche domande di seguito, sei nel posto giusto.
- Si blocca in Java
- Esempio di blocco Java e blocco della concorrenza rispetto a sincronizzato
- Esercitazione sulla concorrenza Java – Blocchi rientranti
- sincronizzazione – Utilizzo corretto di blocco/sblocco per Java
- java – Sincronizzazione vs Blocco
- esempio di sblocco java lock
- meccanismo di blocco in java
- java lock sblocca thread diversi
Iniziamo. Per prima cosa comprendiamo ciascuno di questi termini e poi esamineremo l'esempio di lavoro.
Serratura():
java.util.concurrent.locks
. Un blocco è un meccanismo di sincronizzazione dei thread come i blocchi sincronizzati, tranne per il fatto che i blocchi possono essere più sofisticati dei blocchi sincronizzati di Java. Si tratta di interfacce e classi che forniscono un framework per il blocco e l'attesa di condizioni diverse dalla sincronizzazione e dai monitor integrati.
Sbloccare():
UnLock() rilascia il blocco su Object.
ReentrantLock():
Un ReentrantLock
è di proprietà dell'ultimo thread che si è bloccato correttamente, ma non lo ha ancora sbloccato. Un thread che richiama il lock
verrà restituito, acquisendo correttamente il blocco, quando il blocco non è di proprietà di un altro thread. Il metodo verrà restituito immediatamente se il thread corrente possiede già il blocco.
TryLock():
TryLock() acquisisce il blocco solo se è libero al momento dell'invocazione.
Suggerimento-1
Se stai semplicemente bloccando un oggetto, preferirei usare synchronized.
1 2 3 |
Lock . lock ( ) ; youMethod ( ) ; // Throws a NullPointerException! Lock . unlock ( ) ; // Here you never release the lock! |
Considerando che con sincronizzato, è super chiaro e impossibile sbagliare:
1 2 3 |
synchronized ( myObject ) { doSomethingNifty ( ) ; } |
Dettagli di esempio:
- Crea classe: CrunchifyLockTutorial.java
- Crea classi interne: Company e CrunchifyLoop
- Da Main creare due oggetti di classe Company
- Avvia thread loop per 10 su quegli oggetti
- Mentre Company1 parla con Company2, blocca un oggetto. Se allo stesso tempo – se
Company2
vuole parlare conCompany1
allora dice – Conflicting – Lock esiste già. (Entrambe le società sono già in discussione).
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 ( ) ) ; } } } } |
Produzione:
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 |
Suggerimento-2

Puoi ottenere tutto ciò che le utilità in java.util.concurrent
fanno con le primitive di basso livello come synchronized
, volatile
o wait
.