d*****h 发帖数: 8 | 1 One brother here posted a question he was asked in interview. I am trying to
give an answer. Please comment on it.
Thanks
// 实现两个函数: H() and O(), 这两个函数会被多线程调用。当一个线程调用H或O时
// ,如果当前已经有至少两个线程call H和一个线程call O。那么让两个call H和一个
// call O的线程返回(产生一个水分子),其他的都block
package Solution;
import java.util.concurrent.*;
import java.
public class H2O implements Runnable
{
private int[] H = new int[2];
private int O;
private Semaphore[] HCS = null;
private Semaphore[] HPS = null;
private Semaphore OCS = null;
private Semaphore OPS = null;
private Semaphore TCS = null;
private Semaphore WS = null;
public H2O ()
{
}
public void SetSemaphores(
Semaphore[] hcs,
Semaphore[] hps,
Semaphore ocs,
Semaphore ops,
Semaphore tcs,
Semaphore ws)
{
HCS = hcs;
HPS = hps;
OCS = ocs;
OPS = ops;
TCS = tcs;
WS = ws;
}
public void run()
{
try
{
TCS.acquire();
if (HPS[0].tryAcquire())
{
WS.acquire();
H[0] = 1;
WS.release();
}
else if (HPS[1].tryAcquire())
{
WS.acquire();
H[1] = 1;
WS.release();
}
else if (OPS.tryAcquire())
{
WS.acquire();
O = 0;
WS.release();
}
}
catch (Exception e)
{
}
}
public static void main(String[] args)
{
Semaphore[] HCS = new Semaphore[2];
HCS[0] = new Semaphore(0);
HCS[1] = new Semaphore(0);
Semaphore[] HPS = new Semaphore[2];
HPS[0] = new Semaphore(1);
HPS[1] = new Semaphore(1);
Semaphore OCS = new Semaphore(0);
Semaphore OPS = new Semaphore(1);
Semaphore TCS = new Semaphore(3);
Semaphore WS = new Semaphore(1);
for (int i=0; i<1000; ++i)
{
H2O worker = new H2O();
worker.SetSemaphores(HCS, HPS, OCS, OPS, TCS, WS);
new Thread(worker).start();
}
for (int i=0; i<2; ++i)
{
HCS[i].acquire();
}
OCS.acquire();
WS.acquire();
// read H2O
WS.release();
for (int i=0; i<2; ++i)
{
HPS[i].release();
TCS.release();
}
OPS.release();
TCS.release();
}
} |
|