开发者

Unreachable expression after launch of new thread

When the following code is run, it launches the thread r, as the output from it is received but the test phrase is never outputted though there are no errors outputted that would suggest an error. Why is this not able to progress past the thread launch? Will it wait for the thread to be stopped before continuing?

while(x<y){
    Runnable r = new Rule1(2, 0);
    new Thread(r).start();
    System.out.println("value of x is: " + x);
    x++;
}

I have modified the rule1 method so that in completes sooner. Once it completes then the "value of x is" string is written to the console. This would imply that my main method is waiting for the completion of the thread. I thought that by launching a thread it would run separately allowing both the main and the new thread to run simultaneously. Am i wrong in this assumption? This a sample of the code for rule1

    public class Rule1 impl开发者_如何学Pythonements Runnable {

 public Rule1(int z, int q){

        //do stuff

        }

        public void run(){
        }
}


May be the condtion x < y is not true, so that while is not executted


Î can not reproduce the behaviour you are describing; the code

public static void main(String[] args) throws Exception {
    int y = 10;
    int x = 0;
    while(x<y){
        Runnable r = new Runnable() {
            @Override
            public void run() {
                for (;;) {

                }
            }
        };
        new Thread(r).start();
        System.out.println("value of x is: " + x);
        x++;
    }
}

Produces the output

value of x is: 0
value of x is: 1
value of x is: 2
value of x is: 3
value of x is: 4
value of x is: 5
value of x is: 6
value of x is: 7
value of x is: 8
value of x is: 9
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜