wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes annonymous thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "annonymous thread" Watch "annonymous thread" New topic
Author

annonymous thread

srilatha annepu
Greenhorn

Joined: Jun 29, 2006
Posts: 28
public class Test {

static int i = 0;

public static void main(String[] args) {

Thread t = new Thread(new Runnable(){

public void run(){
for(int j = 0; j < 3; j++)
System.out.println(++i);
}
});

t.start();
System.out.println(i);
}
}

how is the output 0
1
2
3
i thought it was 1
2
3
0
can any one help
Peter MacMillan
Ranch Hand

Joined: Jun 23, 2006
Posts: 34
Run this version of the program:



Notice which line gets run first (ie. which line is printing out the 0). You have, essentially, a race condition: The line at //2 will execute before the line at //1 - printing out the B:0.

The output is likely to be:

B:0
A:1
A:2
A:3

However, it could also be, although less likely:

A:1
B:1
A:2
A:3
Peter MacMillan
Ranch Hand

Joined: Jun 23, 2006
Posts: 34
In other words, the start() method only starts the thread: it will not block (execution will continue).

You can block by calling the join() method, which will cause the current thread wait for that thread to finish.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: annonymous thread
 
Similar Threads
Multi dimensional array
error while running the program
Is this a thread problem.....(..
why does 'break' traverse one more time
Can anyone explain this code from ...Java 2 Part-1 the programmers exam - page 49