gpt4 book ai didi

java - 这个循环怎么能退出呢?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:25:25 25 4
gpt4 key购买 nike

所以,我进行了测试,结果对我来说毫无意义。让我们考虑以下代码:

ThreadStuffCounter counter_1 = new ThreadStuffCounter(1);
while(counter_1.doProceed) {
Thread.sleep(500);
Thread thread = new Thread(counter_1);
thread.start();
}

使用Runnable如下:

package test;

public class ThreadStuffCounter implements Runnable {
public volatile boolean doProceed = true;
private int id = -1;
public volatile int i = -1;
public ThreadStuffCounter(int id) {
this.id = id;
}

@Override
public void run() {
for (i = 0; i < 10; i++) {
System.out.println("i = " + i + " in runnable id = " + id);
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
doProceed = false;
}
}

只有一个计数器实例在线程之间共享。另一个线程启动所需的时间比 counter.doProceed 上的增量要少,据我所知永远不会设置为 false 并且循环应该无限期地继续,直到我退出内存异常,无法启动更多线程。

循环怎么可能退出?

编辑:修改代码以确保下面的答案是正确的。

package test;

public class ThreadStuffCounter implements Runnable{

public volatile boolean doProceed = true;
private int id = -1;
volatile int i = -1;
public ThreadStuffCounter(int id){
this.id = id;
}

@Override
public void run() {
i = 0;
while (i < 10){
System.out.println("i = " + i + " in runnable id = " + id +
"; from thead id = " + Thread.currentThread().getId());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
}
ThreadStuff.doProceed = false;
}

package test;

public class ThreadStuff {

public static volatile boolean doProceed = true;

public static void main (String[] args) throws InterruptedException{
ThreadStuffCounter counter_1 = new ThreadStuffCounter(1);
while(doProceed){
Thread.sleep(500);
Thread thread = new Thread(counter_1);
thread.start();
}
}

此外,如果您正在运行 i < n,则似乎需要 n 个线程。您需要很多,以便 n 个线程同时递增。

最佳答案

当至少有一个线程执行了for循环且i值大于或等于10时,doProceed变量将被false(是的,这可能会发生),并且由于它是 volatile,这将停止执行创建和启动新线程的 while 循环。然后,由所有线程完成 for 循环的代码执行,然后完成它们的执行。这似乎是因为在您的环境中启动新线程的时间比当前线程完成其执行的时间慢。另外,请注意多个线程可能会增加 i 值,这将加速 for 循环的执行。

如果您循环到更高的值(未测试),那么这可能会产生无限循环,并且当没有足够的资源来创建和启动新线程时,应用程序将中断。


在使用限制为 10、50 和 1000 进行了一些测试之后。我注意到当你有一个更大的值时,由于创建了很多线程,它们都会增加 i 的值同时 i 开始慢慢接近 for 循环中设置的限制值。我当前环境的描述:

  • 操作系统:Windows 7 Professional 64 位
  • 处理器:Intel(R) Core(TM) i5-2520M CPU @ 2.50GHz(4 个 CPU),~2.5GHz
  • 内存:8192MB

关于java - 这个循环怎么能退出呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25166568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com