I received this task from one recruiter. His client was looking for a java programmer and they wanted to check my knowledge of Java. I should to create a class that represents a synchronised queue.
Here is my version of a linked synchronised queue. I had to create to inner classes as well.
Here is my version of a linked synchronised queue. I had to create to inner classes as well.
package queue;
/**
*
* @author Alex
*/
/* Synchronised Queue - class SynchQ */
public class SynchQ {
private final Info inf;
private boolean IsEmpty;
/* Inner class FIFOnode */
final class FIFOnode {
Object value;
FIFOnode next;
/* Constructor of FIFOnode */
FIFOnode(Object v, FIFOnode n)
{
value = v;
next = n;
}
}
final class Info{
FIFOnode head;
FIFOnode last;
Info(){
this.last = new FIFOnode(null, null);
this.head = this.last;
}
}
/* Creates a new Queue object. */
public SynchQ ()
{
/* TODO: Implement this method. */
this.IsEmpty = true;
this.inf = new Info();
}
/* Puts an object at the end of the queue. */
public void put(Object obj)
{
/* TODO: Implement this method. */
FIFOnode newNode = new FIFOnode(obj, null);
synchronized (this.inf)
{
this.inf.last.next = newNode;
this.inf.last = newNode;
}
this.IsEmpty = false;
}
/* Gets an object from the beginning of the queue. The object is
* removed from the queue. If there are no objects in the queue,
* returns null.
*/
public Object get()
{
Object x = null;
synchronized (this.inf)
{
FIFOnode first = this.inf.head.next;
if (first != null)
{
x = first.value;
this.inf.head = first;
}
if (this.inf.head.next == null) this.IsEmpty = true;
}
return x;
}
public boolean isEmpty() {
return this.IsEmpty;
}
}
Here is a classes for testing of my queue:package queue;
/**
*
* @author Alex
*/
class SomeClass {
public int x = 10;
SomeClass(int a){
this.x = a;
}
}
public class Queue {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
SomeClass some1 = new SomeClass(10);
SomeClass some2 = new SomeClass(20);
SomeClass some3 = new SomeClass(30);
SynchQ Q = new SynchQ();
Q.put(some1);
Q.put(some2);
Q.put(some3);
System.out.println(Q.isEmpty());
SomeClass s1;
if(!Q.isEmpty())
{ s1 = (SomeClass)Q.get();
System.out.println(s1.x);
System.out.println(Q.isEmpty());
}
if(!Q.isEmpty())
{ s1 = (SomeClass)Q.get();
System.out.println(s1.x);
System.out.println(Q.isEmpty());
}
if(!Q.isEmpty())
{ s1 = (SomeClass)Q.get();
System.out.println(s1.x);
System.out.println(Q.isEmpty());
}
System.out.println(Q.isEmpty()+"AAA");
if(!Q.isEmpty())
{ s1 = (SomeClass)Q.get();
System.out.println(s1.x);
System.out.println(Q.isEmpty());
}
}
}

No comments:
Post a Comment