Java Memory Model
Runnable
count
will be shared, since it stores in Heap. To avoid this, you need to create a new Runnable Object for each thread.
However, the object that implemented in run is a local variable and will be created separately.
If you want your object to be shared, then declear it on the Main and pass it over to your Runnable Object.
Also, you can use synchronized
to avoid data race in sharedObject case:
synchronized(this){
this.count++;
}
package com.guanlun.concurrency;
public class MyRunnable implements Runnable{
private int count = 0;
/** shared Object
private MyObject myObject = new MyObject();
public MyRunnable() {}
public MyRunnable(MyObject myObject) {
this.myObject = myObject;
}
**/
@Override
public void run(){
// independent object
// MyObject myObject = new MyObject();
System.out.println(myObject);
for(int i=0; i<1_000_000; i++){
this.count++;
}
System.out.println(
Thread.currentThread().getName()
+ ":" + this.count);
}
}
SharedObject
package com.guanlun.concurrency;
public class SharedObject {
public static void main(String[] args){
Runnable runnable = new MyRunnable();
Thread thread1 = new Thread(runnable, "Thread1");
Thread thread2 = new Thread(runnable, "Thread2");
thread1.start();
thread2.start();
}
}
/**
com.guanlun.concurrency.MyObject@265f681d
com.guanlun.concurrency.MyObject@4a9473e1
Thread1:151931
Thread2:1017410
**/
SeparateObject
package com.guanlun.concurrency;
public class SeparateObject {
public static void main(String[] args){
/**
MyObject myObject = new MyObject();
Runnable runnable1 = new MyRunnable(myObject);
Runnable runnable2 = new MyRunnable(myObject);
com.guanlun.concurrency.MyObject@2b530204
com.guanlun.concurrency.MyObject@2b530204
Thread1:1000000
Thread2:1000000
**//
Runnable runnable1 = new MyRunnable();
Runnable runnable2 = new MyRunnable();
Thread thread1 = new Thread(runnable1, "Thread1");
Thread thread2 = new Thread(runnable2, "Thread2");
thread1.start();
thread2.start();
}
}
/**
com.guanlun.concurrency.MyObject@3fff3728
com.guanlun.concurrency.MyObject@15b5d244
Thread1:1000000
Thread2:1000000
**/