-
Notifications
You must be signed in to change notification settings - Fork 100
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
61 additions
and
6 deletions.
There are no files selected for viewing
67 changes: 61 additions & 6 deletions
67
src/main/java/com/diguage/truman/concurrent/SynchronizedTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} | ||
} | ||
} |