Swing中的TimerTasks

时间:2010-10-19 14:53:01

标签: java swing timer

我正在尝试编写一个消息确认应用程序,我需要: a)在消息队列中添加每条新消息。只需使用Arraylist创建消息队列。 b)通知timertask在50秒内预期对消息进行确认,因此要使其休眠50秒或在收到确认时唤醒。

实施此操作的最佳做​​法是什么?

由于

2 个答案:

答案 0 :(得分:1)

我不太清楚你的需求是什么。这与Swing或计时器有什么关系?你在这里处理什么样的线程?我会做一些假设并提出一些建议。

听起来您想要将消息放入队列中,然后等待收到响应,或者最多50秒。你应该看看BlockingQueue。它是线程安全的,你可以等待一段特定的时间让另一个线程放入其中。这似乎对消息/确认问题有用。

BlockingQueue<MSG> queue = new LinkedBlockingQueue<MSG>();

// put a message in the queue
queue.put( msg );

// have a thread wait on the queue until something is available in it
MSG msg = queue.poll( 50, TimeUnit.SECONDS );

我需要更多有关您问题的详细信息,以获得更具体的帮助。

答案 1 :(得分:0)

我认为你想要一些机制,在特定间隔之后需要更新,你可以使用线程并根据间隔要求设置睡眠,如:

public void run() {

    while (Start == true) {
        getMessage();      //yourmethod();
        try {
            Thread.sleep(50);
        } catch (InterruptedException ie) {
            stop();
        }
    }
}