views:

64

answers:

2

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 implements Runnable {

 public Rule1(int z, int q){

        //do stuff

        }

        public void run(){
        }
}
A: 

Î 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
meriton
+1  A: 

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

Telcontar
I get into the loop to run the thread and get its result, and then nothing more, so the value of x<y is true
pie154
Have you tested that the Rule1 constructor ends? If not the new Thread(r).start(); is never reached
Telcontar
It was a problem with the constructor method. Thanks
pie154