JUnit tests
This commit is contained in:
@@ -40,7 +40,7 @@ public class App {
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
Mutex mutex = new Mutex();
|
||||
Jar jar = new Jar(mutex);
|
||||
Jar jar = new Jar(1000, mutex);
|
||||
Thief peter = new Thief("Peter", jar);
|
||||
Thief john = new Thief("John", jar);
|
||||
peter.start();
|
||||
|
@@ -37,16 +37,17 @@ public class Jar {
|
||||
/**
|
||||
* The resource within the jar.
|
||||
*/
|
||||
private int beans = 1000;
|
||||
private int beans;
|
||||
|
||||
public Jar(Lock lock) {
|
||||
public Jar(int beans, Lock lock) {
|
||||
this.beans = beans;
|
||||
this.lock = lock;
|
||||
}
|
||||
|
||||
/**
|
||||
* Method for a thief to take a bean.
|
||||
*/
|
||||
public boolean takeBean(Thief thief) {
|
||||
public boolean takeBean() {
|
||||
boolean success = false;
|
||||
try {
|
||||
lock.acquire();
|
||||
|
@@ -32,6 +32,13 @@ public class Mutex implements Lock {
|
||||
*/
|
||||
private Object owner;
|
||||
|
||||
/**
|
||||
* Returns the current owner of the Mutex, or null if available
|
||||
*/
|
||||
public Object getOwner() {
|
||||
return owner;
|
||||
}
|
||||
|
||||
/**
|
||||
* Method called by a thread to acquire the lock. If the lock has already
|
||||
* been acquired this will wait until the lock has been released to
|
||||
@@ -51,8 +58,10 @@ public class Mutex implements Lock {
|
||||
*/
|
||||
@Override
|
||||
public synchronized void release() {
|
||||
owner = null;
|
||||
notify();
|
||||
if (Thread.currentThread() == owner) {
|
||||
owner = null;
|
||||
notify();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -51,7 +51,7 @@ public class Thief extends Thread {
|
||||
public void run() {
|
||||
int beans = 0;
|
||||
|
||||
while (jar.takeBean(this)) {
|
||||
while (jar.takeBean()) {
|
||||
beans = beans + 1;
|
||||
System.out.println(name + " took a bean.");
|
||||
}
|
||||
|
Reference in New Issue
Block a user