-1

我想做两节课。One ( class Mover) 正在更改 other( class Window) 用来重绘每个1/30 seconds. 我想让它们交替工作(Mover,Window,Mover,Window,Mover,Window,Mover,Window ...)。Mover在等待时正在计算,Window然后在重新绘制时正在Mover等待Window

我正在寻找可以工作的线程队列

q.next(); next thread is awakening and the current is going to the end to wait

但没有找到。如何以最简单的方式做到这一点。

将有许多搬运工和一扇窗户。

4

2 回答 2

0

由于任务应该可以互换运行,因此无需使用单独的线程来运行任务,因为很难获得正确的并发性。使用 ScheduledExecutorService 在单个线程中定期运行逻辑。

    ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
    ses.schedule(new Runnable(){
        public void run(){
            mover.run();
            window.run();
        }
    }, 1000/30, TimeUnit.MILLISECONDS);
于 2013-04-13T07:33:44.913 回答
0

听起来您正在尝试解决生产者-消费者之类的问题。可能你可以在一些常见的锁上同步移动器/窗口,然后使用等待/通知功能。像下面的东西

class Lock {
  public static Lock INSTANCE = new Lock();
}

class Mover {

  public void move() {
    synchronized(Lock.INSTANCE) {
       //do the move
       Lock.INSTANCE.notifyAll();
       Lock.INSTANCE.wait();
    }
  }

}

class Window {

  public void paint() {
    synchronized(Lock.INSTANCE) {
       //do the paint
       Lock.INSTANCE.notifyAll();
       Lock.INSTANCE.wait();
    }
  }

}
于 2013-04-13T07:29:36.460 回答