Friday, 15 January 2010

java - Can you call the same method on different threads? -



java - Can you call the same method on different threads? -

really noob question know i'm trying understand how methods , threads work amateur programmer. i'm sure fundamental lack of understanding on part nice person can set me straight.

what wondering if phone call same method multiple times using multiple threads create sandboxed versions of each method deed independently of each other or can interfere each other. illustration i've knocked simple code below seek illustrate mean.

so in illustration have method called when button clicked. takes 2 numbers , feeds them sec method adds them , returns result. seems straight forward. imagine wanted calculation using same method didn't want wait first calculation finish. invoke method adds numbers on separate thread doesn't hold ui thread. cool. ok if twice? or 3 times?

what i'm trying inquire when "dosum" called first time below numbers passed 10 , 20. code runs method on separate thread , should homecoming reply 30. sec time called numbers 30 , 50 , result should 80. if reason calculation in first thread still going on overwritten when phone call same method sec time? result1 ever in danger of beingness returned 80 or 140?

does create sense anyone?

public void onbuttonclicked(view v) { int number1; int number2; int result1, result2, result3; //first callculation -------------------------------------- number1 = 10; number2 = 20; thread t1 = new thread(new runnable() { public void run() { result1 = dosum(number1, number2); } }); t1.start(); //second callculation ----------------------------------- number1 = 30; number2 = 50; thread t2 = new thread(new runnable() { public void run() { result2 = dosum(number1, number2); } }); t2.start(); //third callculation ----------------------------------------- number1 = 60; number2 = 80; thread t3 = new thread(new runnable() { public void run() { result3 = dosum(number1, number2); } }); t3.start(); } public static int dosum(int a, int b) { int result = + b; homecoming result; }

there 2 things should know.

if 2 threads phone call same method, each thread have different stack frame method. so, method local variables thread safe. changes made in local variables of 1 method not interfere other thread's changes.

you should (usually) worry thread-safety / interference when have shared resource beingness modified both threads.

ps : dosum() little processing. smart jvm might inline method.

java android multithreading android-studio

No comments:

Post a Comment