Salida inesperada en un programa multiproceso
Frecuentes
Visto 163 veces
3
class ThreadSafe implements Runnable {
int arr[]=new int[]{1,2,3,4,5};
int sum=0;
public void run() {
int result=sum();
System.out.println("for "+Thread.currentThread().getName()+"the value is"+result);
}
public int sum() {
for(int i=0;i<5;i++) {
sum=sum+arr[i];
System.out.println("calculating sum for thread"+Thread.currentThread().getName()+"sum ="+sum);
try {
Thread.sleep(10);
} catch(Exception e) {}
}
return sum;
}
public static void main(String...d) {
ThreadSafe ts=new ThreadSafe();
ThreadSafe ts1=new ThreadSafe();
Thread t=new Thread(ts);
Thread t1=new Thread(ts1);
t1.start();
t.start();
}
}
I was expecting the output not to come 15. because the sum method is not synchronized so more then one thread can execute the sum method at the same time
What I was expecting that because the 2 thread's will execute the sum method instantly so the output should not be 15 because the first thread will update the value of sum to some value which will be read by the another thread.
So my question is why the output of the program come out the way I'm expecting even though i haven't synchronized the sum() method?
2 Respuestas
7
You're creating two instances of ThreadSafe
, cada uno con su propio sum
Instancia variable.
If you want them to overwrite each other (I'm assuming this is just playing around), create two Thread
s on the same instance of ThreadSafe
. Also, mark your sum
variable as volatile to indicate that it can be changed by another thread (to avoid internal caching of the value if the compiler detects that it is not changed elsewhere within the method).
Por ejemplo, cambie su main
método para esto:
public static void main(String...d) {
ThreadSafe ts=new ThreadSafe();
Thread t=new Thread(ts);
Thread t1=new Thread(ts);
t1.start();
t.start();
}
And the beginning of your ThreadSafe
definición de clase a esto:
class ThreadSafe implements Runnable {
int arr[]=new int[]{1,2,3,4,5};
volatile int sum=0;
Respondido 27 ago 12, 14:08
that means if i will declare sum as a local variable in the method then the result will come as i'm expecting - kTiwari
@krishnaChandra: No, the opposite. To keep your code as it is now (with two instances of ThreadSafe
, you'd need to make the sum
variable static
. But why not just create two Thread
objects off of the same ThreadSafe
¿ejemplo? - adam robinson
@krishnaChandra No, but you can make it static
por ejemplo. - brimborio
@adam :sir Can you please provide the code you are explaining in your answer. - kTiwari
@AdamRobinson: ya after doing what you suggest i got 30 by each of the thread.but still confusing with the code i declared the sum method as synchronized got 15 for the first thread ......ok ...but why 30 is the output by the second thread it should be the 15 again - kTiwari
0
Because you have two instances of ThreadSafe
being handled by different threads. For producing your desired result it should be like one instance and multiple threads working on that same instance
Respondido 27 ago 12, 16:08
Or the two instances sharing a single variable. - brimborio
@brimborium: It seems more idiomatic (to me) to have two threads operating on the same instance, though obviously either would work in this case. - adam robinson
@AdamRobinson I agree, though sharing a single variable might be easier to understand for a beginner... - brimborio
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas java multithreading or haz tu propia pregunta.
add volatile to sum. It indicats that it is concurrently changed. - gregory561
arr
is not static, each ThreadSafe is getting its own copy. Neither issum
. - Wug¿Qué pasa con el código? -> For starters, the formatting (or the lack of it)... ;) - brimborium
@Wug: Your point is well made (see my answer), but he's modifying the
sum
variable, not the source array. - Adam Robinson