Java 멀티스레드 Lock 객체 공통 방법(3)

4261 단어 Java 다중 스레드
다음은 다음과 같은 몇 가지 방법을 연습해 봅시다: isHeldByCurrentThread (): 현재 라인이 이 잠금을 유지하고 있는지 조회 isFair (): Lock이 공평하게 잠겨 있는지 판단 (): lock이 임의의 라인에 소지되어 있는지 조회합니다.
package com.lenovo.plm.dms.p23;

import java.util.concurrent.locks.ReentrantLock;

public class Service {

    private ReentrantLock lock;

    public Service(boolean isfair){
        this.lock = new ReentrantLock(isfair);
    }

    public void service(){
        System.out.println("To check if the current thread hold the lock.."+lock.isHeldByCurrentThread());
        System.out.println("To check if it is a fair lock:"+lock.isFair());
        System.out.println("To check if the lock is locked by any thread."+lock.isLocked());
        lock.lock();
        System.out.println("To check if it is a fair lock:"+lock.isFair());
        System.out.println("To check if the current thread hold the lock.."+lock.isHeldByCurrentThread());
        System.out.println("To check if the lock is locked by any thread."+lock.isLocked());
        lock.unlock();
    }
}
package com.lenovo.plm.dms.p23;

public class Main {

    public static void main(String[] args) {
        final Service service = new Service(true);
        Runnable runnable = new Runnable(){
            @Override
            public void run() {
                // TODO Auto-generated method stub
                service.service();
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();

        final Service service2 = new Service(false);
        runnable = new Runnable(){
          @Override
            public void run() {
                // TODO Auto-generated method stub
                service2.service();
            }  
        };
        thread = new Thread(runnable);
        thread.start();
    }
}

실행 결과: To check if the current thread hold the lock...false To check if it is a fair lock:true To check if the lock is locked by any thread.false To check if it is a fair lock:true To check if the current thread hold the lock..true To check if the lock is locked by any thread.true To check if the current thread hold the lock..false To check if it is a fair lock:false To check if the lock is locked by any thread.false To check if it is a fair lock:false To check if the current thread hold the lock..true To check if the lock is locked by any thread.true

좋은 웹페이지 즐겨찾기