Skip to content

Commit

Permalink
增加 static 与 synchronized 示例
Browse files Browse the repository at this point in the history
  • Loading branch information
diguage committed Sep 28, 2020
1 parent 31f39a5 commit 599846d
Showing 1 changed file with 61 additions and 6 deletions.
67 changes: 61 additions & 6 deletions src/main/java/com/diguage/truman/concurrent/SynchronizedTest.java
Original file line number Diff line number Diff line change
@@ -1,17 +1,72 @@
package com.diguage.truman.concurrent;

import org.junit.jupiter.api.Test;

import java.util.concurrent.locks.LockSupport;

import static com.diguage.truman.concurrent.SynchronizedTest.SynMain.*;

/**
* @author D瓜哥, https://www.diguage.com/
* @since 2020-04-08 19:26
*/
public class SynchronizedTest {
public synchronized void lockMethod() {
System.out.println("lock method");
public synchronized void lockMethod() {
System.out.println("lock method");
}

public void lockObject() {
synchronized (this) {
System.out.println("lock object");
}
}

@Test
public void testInstanceLock() {
SynMain main = new SynMain();
new Thread(main::getInstanceLock1).start();
new Thread(main::getInstanceLock2).start();
new Thread(SynMain::getStaticLock1).start();
new Thread(SynMain::getStaticLock2).start();
LockSupport.park();
}


public static class SynMain {
public static synchronized void getStaticLock1() {
System.out.println("getStaticLock1 get lock, running...");
try {
Thread.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public static synchronized void getStaticLock2() {
System.out.println("getStaticLock2 get lock, running...");
try {
Thread.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public synchronized void getInstanceLock1() {
System.out.println("getInstanceLock1 get lock, running...");
try {
Thread.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public void lockObject() {
synchronized (this) {
System.out.println("lock object");
}
public synchronized void getInstanceLock2() {
System.out.println("getInstanceLock2 get lock, running...");
try {
Thread.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

0 comments on commit 599846d

Please sign in to comment.