gpt4 book ai didi

java - 由于 system.out.println 语句导致线程运行延迟

转载 作者:搜寻专家 更新时间:2023-10-31 20:00:55 26 4
gpt4 key购买 nike

<分区>

在下面的代码中,如果我在 for 循环中使用 sysout 语句,那么代码会在满足条件后执行并进入循环,但是如果我不在循环中使用 sysout 语句,那么无限循环将继续进行,而不会进入 if 内部即使满足 if 条件,也有条件。任何人都可以帮我找出确切的原因。只是一条 sysout 语句使 if 条件变为真。为什么会这样?

代码如下:-

class RunnableDemo implements Runnable {
private Thread t;
private String threadName;

RunnableDemo( String name){
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
for(;;)
{
//Output 1: without this sysout statement.
//Output 2: After uncommenting this sysout statement
//System.out.println(Thread.currentThread().isInterrupted());
if(TestThread.i>3)
{
try {
for(int j = 4; j > 0; j--) {
System.out.println("Thread: " + threadName + ", " + j);
}
} catch (Exception e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
}
}

public void start ()
{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}

}

}

public class TestThread {
static int i=0;
public static void main(String args[]) {

RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {

e.printStackTrace();
}

i+=4;
System.out.println(i);
}
}

无限循环中没有sysout语句的输出:-

在无限循环中使用 sysout 语句输出:-

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