I am trying to understand internal locks in java. I have a program in which I run 2 threads that will loop through and call synchronous methods on one object. I expect both threads to be running in parallel, but it looks like it is running in sequence.
If I enter a dream in a loop, they are executed in random order [as I expected]
public class Synchronized {
private int valueM;
public Synchronized( int value) {
valueM = value;
}
synchronized
public void one() throws InterruptedException
{
System.out.println("Object[" + valueM + "] executing one");
Thread.sleep(100);
System.out.println("Object[" + valueM + "] completed one");
}
synchronized
public void two() throws InterruptedException
{
System.out.println("Object[" + valueM + "] executing two");
Thread.sleep(100);
System.out.println("Object[" + valueM + "] completed two");
}
}
Test code:
@org.junit.jupiter.api.Test
void test_sync() throws InterruptedException
{
Synchronized obj = new Synchronized(1);
Runnable task_one = new Runnable() {
public void run() {
for (int i=0 ; i<10; i++)
{
try {
obj.one();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Runnable task_two = new Runnable() {
public void run() {
for (int i=0 ; i<10; i++)
{
try {
obj.two();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread t1 = new Thread(task_one);
Thread t2 = new Thread(task_two);
t1.start();
t2.start();
t1.join();
t2.join();
}
Conclusion:
Case 1: output:
Object[1] executing one
Object[1] completed one
...10times
Object[1] executing two
Object[1] completed two
...10times
Case 2: output: random order
Object[1] executing one
Object[1] completed one
Object[1] executing two
Object[1] completed two
...
UPDATE: The original problem has been fixed. It seems like this is a random case even in case 1, but I only see it when loading with a lot of iterations (30K).
, for ? - Java-JVM, for-loop " " ( , ?)?