Test For Take In AthreadThis is part of JavaUnitTestChallengeSolved. -- DonWells
Now we can add a threaded take test. I need to reuse the sleepHalfSecond() message so I am going to just move it to Test itself. I also need a good way to look at what the take thread got as output. So I am going to create a static (class) instance variable to hold an array of values as they are received. Because it is static, I had better reset it to empty before I use it. I also add a convenient access method also.
import java.lang.*;
public class TakeThread extends Thread {
public static String output [] = {"z", "z", "z", "z", "z", "z", "z", "z", "z", "z"};
public static int outputLength = 0;
public BoundedBuffer buffer;
TakeThread(BoundedBuffer aBuffer){
buffer = aBuffer;}
public void run (){
take();
take();
take();
take();
take();}
public synchronized void take(){
String taken = "z";
try {
taken = (String) buffer.take();}
catch (InterruptedException exception) {};
output[outputLength++] = taken;}
public static void resetOutput(){
for (int each = 0; each < output.length; each++){
output[each] = "z";};
outputLength = 0;}
public static boolean doesOuputInclude (int aLocation, String aValue){
return output[aLocation] == aValue;}
}
Now the test:
public class TakeThreadTest extends Test {
BoundedBuffer buffer;
TakeThread takeThread;
public void setUp(){
buffer = new BoundedBuffer();
takeThread = new TakeThread(buffer);
buffer.buffer[0] = "a";
buffer.buffer[1] = "b";
buffer.buffer[2] = "c";
buffer.buffer[3] = "d";
buffer.occupied = 4;
buffer.takeAt = 2;
buffer.putAt = 2;}
public void runTest(){
TakeThread.resetOutput();
takeThread.start();
sleepHalfSecond();
should (TakeThread.doesOuputInclude(0, "c"), "first out should be c");
should(TakeThread.doesOuputInclude(1, "d"), "second out should be d");
should(TakeThread.doesOuputInclude(2, "a"), "third out should be a");
should(TakeThread.doesOuputInclude(3, "b"), "fourth out should be b");
should(buffer.occupied == 0, "The buffer should be empty");
should(buffer.takeAt == 2, "takeAt should be 2 again");
onePut("e");
waitForTakeToFinish();
should (TakeThread.doesOuputInclude(4, "e"), "last out should be e");}
public String take(){
String taken;
try {
taken = (String) buffer.take();}
catch (InterruptedException exception){
taken = "";};
return taken;}
public void onePut(String aString){
try {
buffer.put(aString);}
catch (InterruptedException exception){};}
public void waitForTakeToFinish(){
try {
takeThread.join(1000);}
catch (InterruptedException exception) {};}
}
It runs.
This test is really a duplicate of the original TakeAloneTest?. I could go back and remove it; for now I will just save it. Now we need to look at both threads running together.
EditText of this page
(last edited March 4, 2002)
or FindPage with title or text search