Created
December 16, 2016 00:40
-
-
Save nkcoder/f905175246a0839942cd52dfe2e90dda to your computer and use it in GitHub Desktop.
Semaphore demo
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
package org.nkcoder.module.javatest.concurrent; | |
import java.util.concurrent.Semaphore; | |
import java.util.concurrent.TimeUnit; | |
/** | |
* created by daniel at 12/16/16 08:33 | |
*/ | |
public class SemaphoreTest { | |
public static void main(String[] args) { | |
final Semaphore semaphore = new Semaphore(10); | |
for (int i = 0; i < 20; i++) { | |
new Thread(() -> { | |
try { | |
System.out.println("thread: " + Thread.currentThread().getName() + " start..."); | |
semaphore.acquire(); | |
System.out.println("thread: " + Thread.currentThread().getName() + " process..."); | |
TimeUnit.SECONDS.sleep(3); | |
} catch (Exception e) { | |
System.out.println(e); | |
Thread.currentThread().interrupt(); | |
} finally { | |
semaphore.release(); | |
} | |
System.out.println("thread: " + Thread.currentThread().getName() + " finish..."); | |
}).start(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment