Wednesday, 15 May 2013

multithreading - java thread start method or method -



multithreading - java thread start method or method -

this code came sample ocp/scjp

i'm not sure why printx() called before run(). , why guaranteed?

public class constructororrun extends thread { private int x = 2; public constructororrun() throws exception { x = 5; start(); } public void printx() throws exception { x = x - 1; system.out.print(x); } public void run() { x *= 2; } public static void main(string[] args) throws exception { // todo auto-generated method stub new constructororrun().printx(); } }

i don't think 'guaranteed' right word here. in practice printx finish first, because starting new thread takes huge amount of time relative time taken current running thread litle arithmetic, (uncontended) lock console , write it.

it race condition, though, , bad thought rely on either thing happening first. if programme runs plenty times kinds of interleavings may happen. there's no guarantee thing happen first here, improve avoid making assumptions.

java multithreading

No comments:

Post a Comment