在以下代码中,如果我在循环内部使用sysout语句,那么代码将在条件满足时执行并进入循环,但如果我不在内部使用sysout语句然后循环然后无限循环继续而不进入if条件,即使if条件满足..任何人都可以请帮我找出确切的原因。只是一个sysout语句使if条件成为true。为什么这样?由于system.out.println语句导致运行线程延迟
的代码如下: -
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);
}
}
没有系统输出语句在无限循环输出: - enter image description here
输出与系统输出语句在无限循环: - enter image description here
我也会想你正在运行成挥发性的问题。尝试制作 static int i = 0; static volatile int i = 0;如果现在的行为与生病相同,则用解释提出答案。 –
@Aaron它是一个无限循环,所以他们不断地执行它,正确...?编辑:亚伦离开大楼。 –
@亨克德波尔,我尝试使用易失性,它工作正常。但是,你能解释一下sysout语句做了哪些改变,即使没有使用volatile关键字,代码也能工作。 –