暂停测试执行直到应用程序变为空闲 [英] Suspend test execution until application becomes idle

查看:91
本文介绍了暂停测试执行直到应用程序变为空闲的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实现一些util方法暂停测试(当前线程)执行直到应用程序变为空闲是否可行?

空闲意味着:

1.没有添加任何GUI事件一段时间内的事件队列

2.在同一段时间内没有工作线程运行任何任务。

您能否提供实现/代码片段来跟踪以前的情况闲置?

Is it feasible to implement some util method to suspend test (current thread) execution until application becomes idle?
Idle means:
1. there were no GUI events added to event queue for some period of time
2. there were no worker threads running any tasks for the same period of time.
Could you please provide implementation/code snippets to track previous conditions of idleness?

推荐答案

您可以用自己的实现替换 EventQueue ,如此处所示。下面的变体添加了一个 idle()方法,该方法依赖于任意 THRESHOLD 1000毫秒。

You can replace the EventQueue with your own implementation, as shown here. The variation below adds an idle() method that relies on an arbitrary THRESHOLD of 1000 ms.

import java.awt.AWTEvent;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JFrame;
import javax.swing.JTree;

/**
 * @see https://stackoverflow.com/questions/7976967
 * @see https://stackoverflow.com/questions/3158254
 */
public class EventQueueTest {

    public static void main(String[] args) throws
            InterruptedException, InvocationTargetException {
        EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
        final MyEventQueue q = new MyEventQueue();
        eventQueue.push(q);

        EventQueue.invokeAndWait(new Runnable() {

            @Override
            public void run() {
                JFrame f = new JFrame("Test");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.add(new JTree());
                f.pack();
                f.setVisible(true);
            }
        });
        // Test idle() on initial thread
        for (int i = 0; i < 10; i++) {
            Thread.sleep(2 * MyEventQueue.THRESHOLD);
            System.out.println("Idle: " + q.idle());
        }
    }

    private static class MyEventQueue extends EventQueue {

        private static final int THRESHOLD = 1 * 1000;
        private long last;

        @Override
        public void postEvent(AWTEvent e) {
            super.postEvent(e);
            last = System.currentTimeMillis();
        }

        public boolean idle() {
            return System.currentTimeMillis() - last > THRESHOLD;
        }
    }
}

这篇关于暂停测试执行直到应用程序变为空闲的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆