Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

annonymous thread

 
srilatha annepu
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic