Microsoft Interview Question
SDE-2sCountry: United States
public class ReadWrite {
private int reader = 0;
private int writer = 0;
private int writeRequest = 0;
public void read() throws InterruptedException{
synchronized(this) {
while(writer > 0 || writeRequest > 0) {
wait();
}
reader++;
}
try {
System.out.println(Thread.currentThread().getName() + " is reading");
Thread.sleep(5L * 1000L);
System.out.println(Thread.currentThread().getName() + " reading completed");
}catch(Exception ex) {
ex.printStackTrace();
}
synchronized(this) {
reader--;
notifyAll();
}
}
public void write() throws InterruptedException{
synchronized(this) {
writeRequest++;
while(reader > 0 || writer > 0) {
wait();
}
writeRequest--;
writer++;
}
try {
System.out.println(Thread.currentThread().getName() + " is writing");
Thread.sleep(5L * 1000L);
System.out.println(Thread.currentThread().getName() + " write completed");
}catch(Exception ex) {
ex.printStackTrace();
}
synchronized(this) {
writer--;
notifyAll();
}
}
}
package threads;
public class ReadWrite {
private int reader = 0;
private int writer = 0;
private int writeRequest = 0;
public void read() throws InterruptedException{
synchronized(this) {
while(writer > 0 || writeRequest > 0) {
wait();
}
reader++;
}
try {
System.out.println(Thread.currentThread().getName() + " is reading");
Thread.sleep(5L * 1000L);
System.out.println(Thread.currentThread().getName() + " reading completed");
}catch(Exception ex) {
ex.printStackTrace();
}
synchronized(this) {
reader--;
notifyAll();
}
}
public void write() throws InterruptedException{
synchronized(this) {
writeRequest++;
while(reader > 0 || writer > 0) {
wait();
}
writeRequest--;
writer++;
}
try {
System.out.println(Thread.currentThread().getName() + " is writing");
Thread.sleep(5L * 1000L);
System.out.println(Thread.currentThread().getName() + " write completed");
}catch(Exception ex) {
ex.printStackTrace();
}
synchronized(this) {
writer--;
notifyAll();
}
}
}
in C#, a quick console application:
- Diego August 01, 2019