1
我想使用信號量來實現監視器。我創建了2個課程。緩衝區和ThreadDemo。在Buffer類,我創建方法的put()和get()(我得到的代碼從此頁)使用信號量來實現監視器
public void put(int input) throws InterruptedException {
monitorSemaphore.acquire();
boolean acquired = false;
while (numberInBuffer == size) {
// Equivalent of wait()
if (acquired) {
dec();
notifyCalled.release();
}
inc();
monitorSemaphore.release();
notifyCalled.acquire();
monitorSemaphore.acquire();
acquired = true;
}
// Critical section
buffer[last] = input;
last = (last + 1) % size;
numberInBuffer++;
// Equivalent of notifyAll()
for (int i = val(); i > 0; i--) {
dec();
notifyCalled.release();
}
monitorSemaphore.release();
}
public int get() throws InterruptedException {
monitorSemaphore.acquire();
boolean acquired = false;
while (numberInBuffer == 0) {
// Equivalent of wait()
if (acquired) {
dec();
notifyCalled.release();
}
inc();
monitorSemaphore.release();
notifyCalled.acquire();
monitorSemaphore.acquire();
acquired = true;
}
// Critical section
int temp = buffer[start];
start = (start + 1) % size;
numberInBuffer--;
// Equivalent of notifyA(ll)
for (int i = val(); i > 0; i--) {
dec();
notifyCalled.release();
}
monitorSemaphore.release();
return temp;
}
在課堂上TestThread,我創建Thread-T1,線程T2。但我不能在類Buffer中調用put和Get。
public class TestThread extends Thread {
private Thread t;
private String threadName;
public TestThread(String name) {
threadName = name;
System.out.println("Creating " + threadName);
}
public void run() {
System.out.println("Running " + threadName);
try {
put(2);//I can't call this method
Thread.sleep(5000);
get(); //
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start()
{
System.out.println("Starting " + threadName);
if (t == null)
{
t = new Thread (this, threadName);
t.start();
}
}
public static void main(String[] args) {
TestThread T1 = new TestThread("Thread-1");
T1.start();
TestThread T2 = new TestThread("Thread-2");
T2.start();
}}
如果我的TestThread類中的代碼不正確,請告訴我。謝謝!
如何創建對象TestThread? TestThread T1 = new TestThread(「Thread-1」,???); –
「???」應該是你的Buffer對象。這意味着你需要在初始化線程之前創建一個緩衝區對象。此後,不同的線程可以將相同的緩衝區對象作爲構造函數輸入,然後同時對同一個緩衝區對象進行操作。 – Ray
:)非常感謝你。我明白 ! –