Java:清空循环 [英] Java: Empty while loop

查看:86
本文介绍了Java:清空循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个带有以这种方式执行的while循环的程序:

I'm making a program with while loops that execute in this manner:


  1. 主线程进入while循环。

  2. 在while循环中没有任何反应。

  3. 线程将保持while循环,直到条件满足为止。

  4. 另一个线程运行一个满足上述条件的函数。

  1. Main thread enters a while loop.
  2. Nothing happens in the while loop.
  3. Thread will stay in the while loop until the condition is satisfied.
  4. Another thread runs a function that will satisfy said condition.

这是一个例子:

while(path != null);

类中还有另一个函数将路径设置为null,一旦发生这种情况,主线程应该退出这个循环。另一个函数在另一个线程中调用。

There's another function in the class that will set the path to null, and once that happens the main thread should exit this loop. The other function is called in another thread.

但是,即使path设置为null,主线程也不会退出循环。有什么建议吗?

However, the main thread does not exit the loop even when path is set to null. Any suggestions?

代码:

try 
 { 
  for (Node n:realpath) 
    { 
      Thread.sleep(100); 
      actor.walk(n); 
     }
    Thread.sleep(100); 
 } 
 catch (InterruptedException ex) 
  { 
    Logger.getLogger(VNScreen.class.getName()).log(Level.SEVERE, null, ex); 
  } 
  realpath.clear(); 
  path = null;

if(path == null)
    System.out.println("NULLED PATH");


推荐答案

忙碌的等待非常昂贵。我这样做:

Busy waits are very expensive. I'd do it this way:

Object LOCK = new Object(); // just something to lock on

synchronized (LOCK) {
    while (path != null) {
        try { LOCK.wait(); }
        catch (InterruptedException e) {
            // treat interrupt as exit request
            break;
        }
    }
}

然后设置路径为空,只需调用

Then when you set path to null, just call

synchronized (LOCK) {
    LOCK.notifyAll();
}

(您只需在上同步如果两段代码都在同一个对象中。)

(You can just synchronize on this if both pieces of code are in the same object.)

这篇关于Java:清空循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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