Java 멀티스레드 Lock 객체 공통 방법(3)
4261 단어 Java 다중 스레드
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
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
고정 스레드 수 newFixedThreadPool 스레드 풀 사용10개의 작업을 수행하려면 다음과 같은 5개의 스레드를 지정해야 합니다. 실제 작업 실행 클래스: 실행 결과:...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.