当前位置:嗨网首页>书籍在线阅读

35-案例实现

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

案例实现

根据如下步骤来实现本案例。

1.创建一个 ProducerConsumerTest 类,该类继承了 MultithreadedTestCase

public class ProducerConsumerTest extends MultithreadedTestCase {

2.创建一个字符型 LinkedTransferQueue 的私有对象,并取名为 queue

private LinkedTransferQueue<String> queue;

3.实现一个没有任何参数也没有返回值的 initialize() 方法。在该方法内部,请求父类的 initialize() 方法并初始化队列属性:

@Override
public void initialize() {
  super.initialize();
  queue=new LinkedTransferQueue<String>();
  System.out.printf("Test: The test has been initialized\n");
}

4.实现包含第一个消费者逻辑的 thread1() 方法。在该方法内部,首先调用队列对象的 take() 方法,然后在控制台中打印出返回值:

public void thread1() throws InterruptedException {
  String ret=queue.take();
  System.out.printf("Thread 1: %s\n",ret);
}

5.实现包含第二个消费者逻辑的 thread2() 方法。 waitForTick() 方法使在第一个线程因为使用 take() 方法陷入休眠前保持等待,请求 queue 对象的 take() 方法并输出返回值到控制台中:

public void thread2() throws InterruptedException {
  waitForTick(1);
  String ret=queue.take();
  System.out.printf("Thread 2: %s\n",ret);
}

6.实现包含生产者逻辑的 thread3() 方法。由于线程启动后将保持等待直到两个消费者线程阻塞在 take() 方法上,因此将调用两次 waitForTick() 方法,然后使用 put() 方法向队列中插入两个字符串:

public void thread3() {
  waitForTick(1);
  waitForTick(2);
  queue.put("Event 1");
  queue.put("Event 2");
  System.out.printf("Thread 3: Inserted two elements\n");
}

7.实现 finish() 方法。在该方法中,首先打印相应的提示到控制台上,以表示已经完成测试,再使用 assertEquals() 方法检查是否已经消费完队列中的元素(此时队列的大小应该为0)。

public void finish() {
  super.finish();
  System.out.printf("Test: End\n");
  assertEquals(true, queue.size()==0);
  System.out.printf("Test: Result: The queue is empty\n");
}

8.实现本案例的主类,新建 Main 类和 main() 方法:

public class Main {
  public static void main(String[] args) throws Throwable {

9.创建 ProducerConsumerTest 类型的 test 对象:

ProducerConsumerTest test=new ProducerConsumerTest(;

10.执行 TestFramework 类的 runOnce() 方法开始测试本案例:

System.out.printf("Main: Starting the test\n");
TestFramework.runOnce(test);
System.out.printf("Main: The test has finished\n");