다음과 같은 문제가 있습니다.
FooBar 클래스의 동일한 인스턴스가 두 개의 다른 스레드에 전달됩니다.
스레드 A는 foo()를 호출하지만, 스레드 B는 bar()를 호출합니다.
FooBar를 n번 인쇄합니다-
내 code의 경우 교착 상태에 빠졌을 수 있습니다. 파악할 수 없으며 시간 제한이 초과된 것으로 표시됩니다. code가 어디에 붙어 있는지 이해할 수 없음 내가 잘못된 부분을 친절하게 제안하십시오.
class FooBar {
private int n;
private Semaphore semaphore1;
private Semaphore semaphore2;
public FooBar(int n) {
this.n= n;
semaphore1= new Semaphore(1);
semaphore2= new Semaphore(1);
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i= 0; i < n; i++) {
//printFoo.run() outputs "foo". Do not change or remove this line.
semaphore1.acquire();
printFoo.run();
semaphore1.release();
semaphore2.acquire();
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i= 0; i < n; i++) {
semaphore2.acquire();
semaphore1.acquire();
//printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
semaphore1.release();
semaphore2.release();
}
}
}
Bar by Thread의 인쇄가 완료될 때까지 스레드를 중지하려면, 완전한 프로그램 설명이 제공됩니다.
JiT SaHa2022-01-05 06:37:52
semaphore.acquire()가 있는 이유는 무엇입니까? 음식 방법에서?
Sodrul Amin Shaon2022-01-05 06:31:16