0

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(){
        }
}
pie154
  • 603
  • 3
  • 10
  • 28
  • is your thread spinning hard? it won't wait for the thread to stop. though your code is dangerous as the thread goes out of scope so you won't join it back later. – NG. Oct 21 '10 at 17:06
  • You mean, text "value of x is: " never goes to console? – Nikita Rybak Oct 21 '10 at 17:11
  • Can you post the code for your Rule1 class? It's possible that something in its run method is causing the problem. – highlycaffeinated Oct 21 '10 at 17:14
  • @ highlycaffinenated - Since it is launching a seperate thread should the main thread that this code is from not continue on regardless of whatever happens in this newly created thread? @SB - what do u mean spinning hard? and what do u mean about going out of scopeand won't join back? it runs a method then terminates itself once it achieves a desired result, if that clarifies anything – pie154 Oct 21 '10 at 19:24

2 Answers2

1

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

Telcontar
  • 4,794
  • 7
  • 31
  • 39
0

Î 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
  • 68,356
  • 14
  • 108
  • 175