[英]Unexpected output in multithreaded program
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 我期待输出不会来15.因为sum方法不同步所以多一个线程可以同时执行sum方法
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. 我期待的是因为2个线程会立即执行sum方法所以输出不应该是15,因为第一个线程会将sum的值更新为某个值,该值将被另一个线程读取。
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? 所以我的问题是为什么即使我没有同步sum()方法,程序的输出也按照我期望的方式出现?
You're creating two instances of ThreadSafe
, each with their own sum
instance variable. 您正在创建两个
ThreadSafe
实例,每个实例都有自己的sum
实例变量。
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
. 如果你想让它们互相覆盖(我假设这只是玩游戏),在同一个
ThreadSafe
实例上创建两个Thread
。 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). 此外,将
sum
变量标记为volatile,以指示它可以被另一个线程更改(如果编译器检测到它未在方法中的其他位置更改,则避免对值进行内部缓存)。
For example, change your main
method to this: 例如,将
main
方法更改为:
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
class definition to this: 并且
ThreadSafe
类定义的开头是这样的:
class ThreadSafe implements Runnable {
int arr[]=new int[]{1,2,3,4,5};
volatile int sum=0;
Because you have two instances of ThreadSafe
being handled by different threads. 因为有两个
ThreadSafe
实例由不同的线程处理。 For producing your desired result it should be like one instance and multiple threads working on that same instance 为了产生您想要的结果,它应该像一个实例和多个线程在同一个实例上工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.