Created
December 9, 2017 00:22
-
-
Save stepancheg/2123443416bda050eda50fdec8823f78 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
package demo; | |
import java.util.ArrayList; | |
import java.util.concurrent.atomic.AtomicBoolean; | |
import java.util.concurrent.atomic.AtomicInteger; | |
import java.util.concurrent.locks.LockSupport; | |
public class ParkUnpark { | |
public static void main(String[] args) throws Exception { | |
AtomicInteger count = new AtomicInteger(); | |
AtomicBoolean shutdown = new AtomicBoolean(); | |
Thread t1 = new Thread(() -> { | |
int i = 0; | |
while (!shutdown.get()) { | |
LockSupport.park(); | |
++i; | |
} | |
count.set(i); | |
}); | |
t1.start(); | |
ArrayList<Thread> wakers = new ArrayList<>(); | |
for (int i = 0; i != 5; ++i) { | |
Thread t2 = new Thread(() -> { | |
for (int j = 0; j != 1_000; ++j) { | |
LockSupport.unpark(t1); | |
} | |
}); | |
t2.start(); | |
wakers.add(t2); | |
} | |
for (Thread waker : wakers) { | |
waker.join(); | |
} | |
shutdown.set(true); | |
LockSupport.unpark(t1); | |
t1.join(); | |
System.out.println(count); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment