Skip to content

Instantly share code, notes, and snippets.

@quocthinhle
Created September 25, 2021 14:30
Show Gist options
  • Save quocthinhle/50c971847910b10fc2bb72f0ada08880 to your computer and use it in GitHub Desktop.
Save quocthinhle/50c971847910b10fc2bb72f0ada08880 to your computer and use it in GitHub Desktop.
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
public class ThreadStaticSyncDemo {
public static void main (String[] args) throws InterruptedException {
Thread thread1 = new Thread(() -> {
System.out.println("thread1 before call "+ LocalDateTime.now());
syncMethod("from thread1");
System.out.println("thread1 after call "+LocalDateTime.now());
});
Thread thread2 = new Thread(() -> {
System.out.println("thread2 before call "+LocalDateTime.now());
syncMethod("from thread2");
System.out.println("thread2 after call "+LocalDateTime.now());
});
thread1.start();
thread2.start();
}
private static synchronized void syncMethod (String msg) {
System.out.println("in the sync method "+ msg + " " + LocalDateTime.now());
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment