topic description
while learning the knowledge of multithreading, the result of the following code is not the same as expected. I can"t see what the problem is. Please take a look at it
.sources of topics and their own ideas
what I think is that after the end of the program, the value of staticv is an integer 200000, but each time the result is in 19xxxxxxxxx, which is very close, unlike Synchronize. I don"t know what went wrong. In addition, the code is annotated with the location of-sharp, foo is marked by synchronized, and Synchronize is the instance object of SyncObj rather than SyncObjc.class,. Obviously, there are two instance objects that are called without Synchronize. I think it is wrong if volatile is not added. But the result of the execution seems to be the same. Why? I don"t know what went wrong with my understanding. Please give me your advice. Thank you.
related codes
package concurrency;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class SynchronizedTest {
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
SyncObj obj1 =new SyncObj();
SyncObj obj2 =new SyncObj();
CountDownLatch countDownLatch = new CountDownLatch(20);
for(int i=0;i<10;iPP) {
executor.execute(new TT(obj1,countDownLatch));
executor.execute(new TT(obj2,countDownLatch));
}
countDownLatch.await();
System.out.println("result----------------------"+SyncObj.staticv);
}
}
class SyncObj {
public static volatile int staticv = 0; //-sharp-sharp-sharp-sharp-sharp-sharpvolatile
public synchronized void foo() {
for(int i=0;i<1000;iPP) {
System.out.println(staticv);
staticvPP;
}
}
}
class TT implements Runnable{
public CountDownLatch countDownLatch;
public SyncObj obj;
public TT( SyncObj obj,CountDownLatch countDownLatch) {
this.obj=obj;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
for(int i=0;i<100;iPP) {
obj.foo();
}
countDownLatch.countDown();
}
}