本文介绍了线程需要不断检查else的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public void run()
{
    if (flag)
    {
        infinite Loop...
    }
    else
    {
        infinite Loop...
    }
}

在我的线程中有 if else 语句根据 flag 执行.这里我的 flag 不是静态的,而是在执行程序时动态变化.每次 flag 值更改时,我都希望检查 if-else 条件.假设我的 flagfalse 它将执行 else 部分.现在我的 flag 更改为 true 然后它应该来自 else 并执行 if 部分.这怎么实现???

In my thread there is if else statement which executes based on flag. Here my flag is not static and changes dynamically while executing the program. Every time the flag value changes I want the if-else condition to be checked. Suppose my flag is false it will execute the else part. Now my flag changes to true then it should come out of else and execute if part. How can this be implemented ???

推荐答案

如果一个线程在没有任何退出条件的情况下进入无限循环,那么除非你强制中断,否则你无法改变它的行为.

If a thread enters an infinite loop without any exit condition then you have no way to make it change its behaviour unless you force its interruption.

假设您可以将 if/else 移到外面:

Given that you can just move the if/else outside:

public void run() {
  while (!finished) {
    if (flag) {
      .. true loop iteration ..
    }
    else {
      .. false loop iteration ..
    }
  }
}

请注意,您希望 flagvolatile,以便线程可以使用其最新值.另外不能动态改变的变量是final,而不是static,意义不同.

Mind that you want flag to be volatile so that thread can use its most recent value. In addition variables which can't be changed dynamically are final, not static, which has a different meaning.

如果您被迫分离无限循环,只需在其中放置一个条件:

If you are forced to have separated infinite loops just place a condition in there:

public void run() {
  while (!finished) {
    while (flag) {
      .. true loop iteration ..
    }
    while (!flag) {
      .. false loop iteration ..
    }
  }
}

这篇关于线程需要不断检查else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 05:54
查看更多