import
java.util.concurrent.BlockingQueue;
import
java.util.concurrent.SynchronousQueue;
public
class
SynchronousQAPI<E> {
public
SynchronousQueue<E> synchronousQ;
public
SynchronousQAPI()
{
synchronousQ =
new
SynchronousQueue<E>();
}
public
SynchronousQAPI(
boolean
fair)
{
synchronousQ =
new
SynchronousQueue<E>();
}
public
void
put(E e)
throws
InterruptedException
{
synchronousQ.put(e);
}
public
E take()
throws
InterruptedException
{
return
synchronousQ.take();
}
class
Put
implements
Runnable {
@SuppressWarnings
(
"rawtypes"
)
BlockingQueue SynchronousQueue;
@SuppressWarnings
(
"rawtypes"
)
public
Put(BlockingQueue q)
{
this
.SynchronousQueue = q;
}
@SuppressWarnings
(
"unchecked"
)
@Override
public
void
run()
{
try
{
SynchronousQueue.put(
1
);
System.out.println(
"1 added to synchronous queue."
);
Thread.sleep(
1000
);
}
catch
(InterruptedException e) {
e.printStackTrace();
}
}
}
class
Take
implements
Runnable {
@SuppressWarnings
(
"rawtypes"
)
BlockingQueue SynchronousQueue;
@SuppressWarnings
(
"rawtypes"
)
public
Take(BlockingQueue q)
{
this
.SynchronousQueue = q;
}
@Override
public
void
run()
{
try
{
this
.SynchronousQueue.take();
System.out.println(
"1 removed from synchronous queue."
);
}
catch
(InterruptedException e) {
e.printStackTrace();
}
}
}
public
static
void
main(String[] args)
throws
InterruptedException
{
SynchronousQAPI<Integer> synchronousQueue
=
new
SynchronousQAPI<Integer>();
new
Thread(
new
SynchronousQAPI<>().
new
Put(
synchronousQueue.synchronousQ))
.start();
new
Thread(
new
SynchronousQAPI<>().
new
Take(
synchronousQueue.synchronousQ))
.start();
}
}