add demo for synchronized keyword

add demo for VarHandler
This commit is contained in:
2025-02-28 11:37:34 +08:00
parent a7a720bc00
commit f6514d37a9
3 changed files with 125 additions and 0 deletions

View File

@ -0,0 +1,16 @@
package jvm;
import java.util.Arrays;
public class VarHandleDemo {
public int publicVar =1;
protected int protectedVar =2;
private int privateVar =3;
public int[] publicArrayData ={1,2,3};
@Override
public String toString() {
return STR."VarHandleDemo{publicVar=\{publicVar}, protectedVar=\{protectedVar}, privateVar=\{privateVar}, arrayData=\{Arrays.toString(publicArrayData)}}";
}
}

View File

@ -0,0 +1,70 @@
package threaddemo.dataracing;
public class SyncDemo {
public synchronized static void methodA() {
System.out.println("enter static method methodA, sleep for 1s");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("leaving methodA");
}
public synchronized static void methodB() {
System.out.println("enter static method methodB, sleep for 1s");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("leaving methodB");
}
public synchronized void methodC() {
System.out.println("enter method methodC, sleep for 1s");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("leaving methodC");
}
public void methodD() {
System.out.println("enter method methodD, sleep for 1s");
synchronized (SyncDemo.class) {
System.out.println("start run methodD");
try {
Thread.sleep(1000);
} catch ( InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("leaving methodD");
}
public static void main(String[] args) {
SyncDemo sd = new SyncDemo();
long start = System.currentTimeMillis();
Thread t1 = new Thread(SyncDemo::methodA);
Thread t2 = new Thread(SyncDemo::methodB);
Thread t3 = new Thread(sd::methodC);
Thread t4 = new Thread(sd::methodD);
t1.start();
t2.start();
t3.start();
t4.start();
try {
t1.join();
t2.join();
t3.join();
t4.join();
System.out.println(STR."cost: \{System.currentTimeMillis() - start}");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}