Java多线程问题 子线程无限循环导致主线程无法执行

代码如下,想知道为什么main方法中的if语句无法执行?想的是让if判断程序是否结束,但是程序好像一直结束不了

class Left extends Thread
{
int n = 0;
public void run()
{
while(true)
{
n++;
System.out.printf("\n%s","Left");
try
{
sleep((int)(Math.random()*100)+100);
}
catch(InterruptedException e) {}
}
}
}

class Right extends Thread
{
int n = 0;
public void run()
{
while(true)
{
n++;
System.out.printf("\n%40s","Right");
try
{
sleep((int)(Math.random()*100)+100);
}
catch(InterruptedException e){}
}
}
}

public class Example8_3
{
public static void main(String args[])
{
Left left = new Left();
Right right = new Right();
left.start();
right.start();

while(true)
{
if(left.n>=8 || right.n>=8) // 这一句好像永远也运行不到
System.exit(0);
}
}
}

我测试了一下,这个判断语句是已经执行了,就在第一句语句之前进行的,不信可以把if判断去掉,程序就一句也不执行。说明什么,说明这个语句exit已经执行,不过,对于线程的终结应该是在线程的循环内部进行定义,在线程的外部限制,好像不合适。

class Left extends Thread{
    int n = 0;
    public void run(){
        while(n <= 8){        
            n++;
            System.out.printf("\n%s","Left");
            System.out.print(n);
            try{
                sleep((int)(Math.random()*100)+100);
            }
            catch(InterruptedException e) {}
        }
    }
}

追问

就我是想在主线程main中判断left和right中的n是否到了8,到了就exit结束所有线程嘛,但是按我那样写似乎是main中读取不了n进行判断,如果把main方法的循环改成:
while(true)
{
if(left.n>=8 || right.n>=8) {
System.out.println("end");
System.exit(0);
}
}
结果不会输出“end”诶,想知道为什么不行

温馨提示:内容为网友见解,仅供参考
第1个回答  2018-11-19
在主线程的循环中输出,可以看到是主线程忙,没执行子线程,等一段时间就能结束了。
相似回答