Reputation: 15882
I am learning java and about threads and had this code:
Integer target = (int) (Math.random() * 1000);
System.out.println("The number is " + target);
Monitor mThread = new Monitor();
mThread.start();
Finder finder1 = new Finder(0,249,target,mThread);
Finder finder2 = new Finder(250,499,target,mThread);
Finder finder3 = new Finder(500,749,target,mThread);
Finder finder4 = new Finder(750,1000,target,mThread);
Thread t1 = new Thread(finder1,"T1");
t1.start();
mThread.addThread(t1);
Thread t2 = new Thread(finder2,"T2");
t2.start();
mThread.addThread(t2);
Thread t3 = new Thread(finder3,"T3");
t3.start();
mThread.addThread(t3);
Thread t4 = new Thread(finder4,"T4");
t4.start();
mThread.addThread(t4);
The Finder class accepts a range and a number to check to see if it is in that range. When running the code, before using Final variables in Finder, only the last rage of numbers would be used for testing.
I thought the New Finder would instantiate a completely new object, why are the variables from finder1 in scope for finder4 to alter?
Upvotes: 0
Views: 96
Reputation: 3417
Integer is immutable, so you must be referring to another variable, inside the Finder class.
Without the code for Finder it is hard to answer what you've got wrong, but the best guess is your using a shared variable to store target, and then they can alter each other. The original value is never altered though, simply lost in the process when reassigned.
Upvotes: 0
Reputation: 8695
Do you have some code waiting for the threads to finish? Can it be, that only thread with finder1 has enough time to do the calculations and print the result before you exit your program?
Upvotes: 1
Reputation: 116878
I thought the New Finder would instantiate a completely new object, why are the variables from finder1 in scope for finder4 to alter?
If the values are instance fields (i.e. not static
) then finder4
should not have access finder1
s fields. Saying new Finder(...)
definitely does instantiate a completely new object.
Is is possible that the output from the threads is coming back in a different order than you are expecting? It may be that finder1
's thread starts or finishes after finder4
so you are just seeing the results from finder1
at the end.
Upvotes: 1