java - 如何暂停 Runnable() 对象以进行测试

标签 java multithreading concurrency sleep

我有以下情况: 我以这种方式向 NotifyingBlockingThreadPoolExecutor 提交 n 个线程:

while ( index < customers.length ) {
    threadPoolExecutor.submit( new Runnable() {                       
        @Override
        public void run() {
            //callToExternalServiceHere;
            response = mockWebService();
        }
    });
    index++;
}

每个线程都会调用外部 Web 服务,但我们仍然无法使用该服务。所以我最终创建了一个模拟类,它返回包含一些数据的响应。现在我希望能够模拟响应延迟,我怎样才能实现这个目标?

提前致谢

更新:

这是我用来实例化 NotifyingBlockingThreadPoolExecutor 的代码

public static NotifyingBlockingThreadPoolExecutor getThreadPoolExecutor() {
    if ( instance.threadPoolExecutor == null ) {
        int numThread = 0;
        int availableProcessors = Runtime.getRuntime().availableProcessors();
        System.out.println( "CheckMultiTransaction - getThreadPoolExecutor - availableProcessors: " + availableProcessors );
        if ( WSConfiguration.getProperty( WSConstants.THREAD_MULTITRN_NUMTHREAD ) != null ) {
            numThread = Integer.parseInt( WSConfiguration.getProperty( WSConstants.THREAD_MULTITRN_NUMTHREAD ) );
            System.out.println( "CheckMultiTransaction - getThreadPoolExecutor - numThread indicati nella S_SYSTEM: " + numThread );
            numThread = numThread > availableProcessors ? availableProcessors : numThread;
        }
        else {
            numThread = availableProcessors;
        }

        System.out.println( "CheckMultiTransaction - getThreadPoolExecutor - numThread : " + numThread );
        int queueSize = numThread * 2; // recommended - twice the size of the poolSize
        int threadKeepAliveTime = 15;
        TimeUnit threadKeepAliveTimeUnit = TimeUnit.SECONDS;

        long maxBlockingTime = 10;
        TimeUnit maxBlockingTimeUnit = TimeUnit.MILLISECONDS;
        boolean useTimeoutQueue = false;
        if ( WSConfiguration.getProperty( WSConstants.THREAD_MULTITRN_MAXBLOCKINGTIME ) != null ) {
            maxBlockingTime = Long.parseLong( WSConfiguration.getProperty( WSConstants.THREAD_MULTITRN_MAXBLOCKINGTIME ) );
            useTimeoutQueue = true;
        }
        final boolean useTimeoutQueueThread = useTimeoutQueue;
        System.out.println( "THREAD_MULTITRN_MAXBLOCKINGTIME:" + WSConfiguration.getProperty( WSConstants.THREAD_MULTITRN_MAXBLOCKINGTIME ) );

        Callable<Boolean> blockingTimeoutCallback = new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                System.out.println( "blockingTimeoutCallback - useTimeoutQueue:" + useTimeoutQueueThread + " - Thread.currentThread().isInterrupted():" + Thread.currentThread().isInterrupted() );
                if ( useTimeoutQueueThread )
                    return false;
                else
                    return !Thread.currentThread().isInterrupted(); // keep waiting
            }
        };

        instance.threadPoolExecutor = new NotifyingBlockingThreadPoolExecutor( numThread, queueSize, threadKeepAliveTime, threadKeepAliveTimeUnit, maxBlockingTime, maxBlockingTimeUnit, blockingTimeoutCallback );
    }
    return instance.threadPoolExecutor;
}

最佳答案

你绝对可以在mockWebService()方法中调用Thread.sleep(5000)来延迟5秒。或者只是将 Thread.sleep(5000) 放入 Runnable 例如

threadPoolExecutor.submit( new Runnable() {                       
        @Override
        public void run() {
            Thread.sleep(5000);
            //callToExternalServiceHere;
            response = mockWebService();
        }
    });

但是,我宁愿建议您使用一些库进行模拟测试,例如 Mockito,来创建 Web 服务对象的模拟。在这种情况下,您将能够以更灵活的方式管理模拟 Web 服务的行为。例如,要强制模拟 Web 服务进行一些延迟,您可以执行以下操作:

Mockito.doAnswer(new Answer() {
   public Object answer(InvocationOnMock invocation) {
       Thread.sleep(<delay_timeout>);
       return "web_service_response_body_object";
   }})
 .when(webServiceMock).doWebServiceCall();

请参阅 Mockito documentation以及 Mockito.doAnswer 方法 documentation了解更多详情。

关于java - 如何暂停 Runnable() 对象以进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58065880/

相关文章:

java - 为什么在没有同步块(synchronized block)的情况下调用 wait()、notify() 或 notifyAll() 不是编译器错误?

c - 多线程 Linux 程序没有给出预期的输出

c# - 多线程示例 - 我需要锁定字典吗

java - 为什么 synchronized() 的位置很重要?

Java:SingleThreadScheduledExecutor & java.util.concurrent.RejectedExecutionException

Mysql手动自增并发连接数证明

java - 设置 LDAP SecurityPrincipal 值

java - 如何在不覆盖方法本身的情况下覆盖方法的 javadoc?

java - 如何在java中使用递归反转数字序列

java - Spring ThreadPoolTask​​Executor 关闭异步任务