이 글에서는 동기화를 사용하여 Lock 코드를 구현하는 방법을 소개합니다. 다음은 도움이 필요한 친구들이 참고할 수 있는 사례입니다.
방법 1:
public synchronized void a(){ //TODO }
방법 2:
public void b(){ synchronized(this){ //TODO } }
이 두 가지 방법 중 {} 사이에 잠금이 추가됩니다.
public void c() { lock.lock(); try { // TODO } finally { lock.unlock(); } }
이 lock()과 Unlock() 사이에 일종의 잠금이 추가되므로 잠금 기능을 구현하려면 lock()과 Unlock() 두 가지 메서드를 구현하는 방법을 먼저 생각하고 프레임워크를 정의해야 합니다. 다음과 같습니다:
public void lock(){ } public void unlock(){ }
그런 다음 동기화를 사용하여 이 두 가지 방법을 구현하는 방법을 생각해 보세요.
이제는 실제로 약간 더 명확한 아이디어가 있지만 여전히 이 두 가지 방법을 어떻게 채울지 모르겠습니다. 나중에 Lock의 특성을 분석한 다음 다음 코드를 살펴보겠습니다.
public void c() { lock.lock(); //When current thread get the lock, other thread has to wait try { //current thread get in the lock, other thread can not get in // TODO } finally { lock.unlock(); //current thread release the lock } }
이 코드에 몇 가지 설명만 추가하고 다른 작업은 하지 않았습니다. 이 코드를 이해하고 가장 자주 사용되는 단어인 currentthread가 무엇인지 확인하는 데 도움이 될까요? 그런 다음 lock() 및 Unlock( )을 채워 보겠습니다. 방법, 해결책을 찾기 위해 currentthread 키워드를 잡는 데 주의를 기울여야 할까요? 대답은 '예'입니다.
다음으로, 동기화를 사용할 때 스레드를 대기시키는 방법을 분석해 보세요. wait() 메소드를 사용하십시오. 스레드를 깨우는 방법은 무엇입니까? 통지() 메소드를 사용하십시오. 그런 다음 lock() 메서드의 wait() 메서드를 사용하고 Unlock() 메서드의 inform() 메서드를 사용합니다. 그러면 wait()와 inform()을 사용할 때 조건이 있습니다. 어떤 조건을 사용해야 할까요?
현재 잠금이 점유되어 있는지 여부를 판단 조건으로 사용해야 합니다. 잠금이 점유되어 있으면 현재 스레드가 대기합니다. 동기화를 사용할 때 항상 이 조건을 사용해 왔는지 생각해 보세요. 대답은 '예'입니다.
언제 잠금을 해제하고 어떤 조건을 사용하는지 분석해 보겠습니다. 스레드 A가 잠금을 얻으면 스레드 B가 잠금을 해제할 수 있을까요? 물론 그렇지 않습니다. B를 석방할 수 있다면 이는 원칙을 위반하는 것입니다. 스레드 A의 잠금은 스레드 A에 의해서만 해제될 수 있어야 합니다. 따라서 판단 조건은 잠금을 보유하고 있는 스레드가 현재 스레드인지 여부를 판단하는 것입니다. 그렇다면 해제할 수는 없습니다.
이제 전체 코드를 살펴보겠습니다.
package test.lock; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; public class NaiveLock { private static final long NONE = -1; private long owner = NONE; private Boolean isLooked() { return owner != NONE; } public synchronized void lock() { long currentThreadId = Thread.currentThread().getId(); if (owner == currentThreadId) { throw new IllegalStateException("Lock has been acquired by current thread"); } while (this.isLooked()) { System.out.println(String.format("thread %s is waitting lock", currentThreadId)); try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } owner = currentThreadId; System.out.println(String.format("Lock is acquired by thread %s", owner)); } public synchronized void unlock() { if (!this.isLooked() || owner != Thread.currentThread().getId()) { throw new IllegalStateException("Only Lock owner can unlock the lock"); } System.out.println(String.format("thread %s is unlocking", owner)); System.out.println(); owner = NONE; notify(); } public static void main(String[] args) { final NaiveLock lock = new NaiveLock(); ExecutorService executor = Executors.newFixedThreadPool(20, new ThreadFactory() { private ThreadGroup group = new ThreadGroup("test thread group"); { group.setDaemon(true); } @Override public Thread newThread(Runnable r) { return new Thread(group, r); } } ); for (int i = 0; i < 20; i++) { executor.submit(new Runnable() { @Override public void run() { lock.lock(); System.out.println(String.format("thread %s is running...", Thread.currentThread().getId())); try { Thread.sleep(new Random().nextint(1000)); } catch (InterruptedException e) { e.printStackTrace(); } lock.unlock(); } } ); } } }
실행하고 결과를 확인하세요.
Lock is acquired by thread 8 thread 8 is running... thread 27 is waitting lock thread 26 is waitting lock thread 25 is waitting lock thread 24 is waitting lock thread 23 is waitting lock thread 22 is waitting lock thread 21 is waitting lock thread 20 is waitting lock thread 19 is waitting lock thread 18 is waitting lock thread 17 is waitting lock thread 16 is waitting lock thread 15 is waitting lock thread 14 is waitting lock thread 13 is waitting lock thread 12 is waitting lock thread 11 is waitting lock thread 10 is waitting lock thread 9 is waitting lock thread 8 is unlocking Lock is acquired by thread 27 thread 27 is running... thread 27 is unlocking Lock is acquired by thread 26 thread 26 is running... thread 26 is unlocking Lock is acquired by thread 25 thread 25 is running... thread 25 is unlocking Lock is acquired by thread 24 thread 24 is running... thread 24 is unlocking Lock is acquired by thread 23 thread 23 is running... thread 23 is unlocking Lock is acquired by thread 22 thread 22 is running... thread 22 is unlocking Lock is acquired by thread 21 thread 21 is running... thread 21 is unlocking Lock is acquired by thread 20 thread 20 is running... thread 20 is unlocking Lock is acquired by thread 19 thread 19 is running... thread 19 is unlocking Lock is acquired by thread 18 thread 18 is running... thread 18 is unlocking Lock is acquired by thread 17 thread 17 is running... thread 17 is unlocking Lock is acquired by thread 16 thread 16 is running... thread 16 is unlocking Lock is acquired by thread 15 thread 15 is running... thread 15 is unlocking Lock is acquired by thread 14 thread 14 is running... thread 14 is unlocking Lock is acquired by thread 13 thread 13 is running... thread 13 is unlocking Lock is acquired by thread 12 thread 12 is running... thread 12 is unlocking Lock is acquired by thread 11 thread 11 is running... thread 11 is unlocking Lock is acquired by thread 10 thread 10 is running... thread 10 is unlocking Lock is acquired by thread 9 thread 9 is running... thread 9 is unlocking
for 루프를 30번으로 변경하면 결과를 확인하세요. 다시:
Lock is acquired by thread 8 thread 8 is running... thread 27 is waitting lock thread 26 is waitting lock thread 25 is waitting lock thread 24 is waitting lock thread 23 is waitting lock thread 22 is waitting lock thread 21 is waitting lock thread 20 is waitting lock thread 19 is waitting lock thread 18 is waitting lock thread 17 is waitting lock thread 16 is waitting lock thread 15 is waitting lock thread 14 is waitting lock thread 13 is waitting lock thread 12 is waitting lock thread 11 is waitting lock thread 10 is waitting lock thread 9 is waitting lock thread 8 is unlocking Lock is acquired by thread 27 thread 27 is running... thread 8 is waitting lock thread 27 is unlocking Lock is acquired by thread 27 thread 27 is running... thread 26 is waitting lock thread 27 is unlocking Lock is acquired by thread 27 thread 27 is running... thread 25 is waitting lock thread 27 is unlocking Lock is acquired by thread 24 thread 24 is running... thread 27 is waitting lock thread 24 is unlocking Lock is acquired by thread 23 thread 23 is running... thread 24 is waitting lock thread 23 is unlocking Lock is acquired by thread 22 thread 22 is running... thread 23 is waitting lock thread 22 is unlocking Lock is acquired by thread 22 thread 22 is running... thread 21 is waitting lock thread 22 is unlocking Lock is acquired by thread 22 thread 22 is running... thread 20 is waitting lock thread 22 is unlocking Lock is acquired by thread 22 thread 22 is running... thread 19 is waitting lock thread 22 is unlocking Lock is acquired by thread 22 thread 22 is running... thread 18 is waitting lock thread 22 is unlocking Lock is acquired by thread 17 thread 17 is running... thread 17 is unlocking Lock is acquired by thread 16 thread 16 is running... thread 16 is unlocking Lock is acquired by thread 15 thread 15 is running... thread 15 is unlocking Lock is acquired by thread 14 thread 14 is running... thread 14 is unlocking Lock is acquired by thread 13 thread 13 is running... thread 13 is unlocking Lock is acquired by thread 12 thread 12 is running... thread 12 is unlocking Lock is acquired by thread 11 thread 11 is running... thread 11 is unlocking Lock is acquired by thread 10 thread 10 is running... thread 10 is unlocking Lock is acquired by thread 9 thread 9 is running... thread 9 is unlocking Lock is acquired by thread 8 thread 8 is running... thread 8 is unlocking Lock is acquired by thread 26 thread 26 is running... thread 26 is unlocking Lock is acquired by thread 25 thread 25 is running... thread 25 is unlocking Lock is acquired by thread 27 thread 27 is running... thread 27 is unlocking Lock is acquired by thread 24 thread 24 is running... thread 24 is unlocking Lock is acquired by thread 23 thread 23 is running... thread 23 is unlocking Lock is acquired by thread 21 thread 21 is running... thread 21 is unlocking Lock is acquired by thread 20 thread 20 is running... thread 20 is unlocking Lock is acquired by thread 19 thread 19 is running... thread 19 is unlocking Lock is acquired by thread 18 thread 18 is running... thread 18 is unlocking
이 사례를 읽으신 후 방법을 마스터하셨다고 믿습니다. 더 흥미로운 정보를 보려면 PHP 중국어 웹사이트의 다른 관련 기사에 주목하세요!
관련 자료:
PHP가 스택 데이터 구조 및 대괄호 일치 알고리즘을 구현하는 방법에 대한 자세한 코드 예
PHP에서 가장 간단한 문자열 일치 알고리즘, PHP 일치 알고리즘_PHP 튜토리얼
위 내용은 동기화를 사용하여 잠금 코드를 구현하는 방법에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!