由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - Solution for interview question posted here before
相关主题
请教L家生成H2O水分子的题。failed bloomberg phone interview
求问一道multithreading问题A家面经
Bloomberg面经突击15天算法能搞定大公司的技术面试吗
Java concurrency 面试题skype phone screen 经
Java编程讨论:LinkedIn的H2O问一道amz的oo题
LinkedIn 面经问个thread synchronization的问题
想问一下那道H2O的多线程题问板上的兄弟,简历里写会java,是要一定要会 servelet,mulithread,和网络这些外延的吗?
为什么说semaphore是一种进程间的通信方式。贡献T家新鲜面经,求个bless
相关话题的讨论汇总
话题: semaphore话题: hps话题: hcs话题: ocs话题: tcs
进入JobHunting版参与讨论
1 (共1页)
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();
}
}
1 (共1页)
进入JobHunting版参与讨论
相关主题
贡献T家新鲜面经,求个blessJava编程讨论:LinkedIn的H2O
A 家的 design 题目确实不好搞LinkedIn 面经
面经想问一下那道H2O的多线程题
Java 多线程 的架构如何改进? (转载)为什么说semaphore是一种进程间的通信方式。
请教L家生成H2O水分子的题。failed bloomberg phone interview
求问一道multithreading问题A家面经
Bloomberg面经突击15天算法能搞定大公司的技术面试吗
Java concurrency 面试题skype phone screen 经
相关话题的讨论汇总
话题: semaphore话题: hps话题: hcs话题: ocs话题: tcs