Skip to content

Instantly share code, notes, and snippets.

@nkcoder
Created December 16, 2016 00:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nkcoder/f905175246a0839942cd52dfe2e90dda to your computer and use it in GitHub Desktop.
Save nkcoder/f905175246a0839942cd52dfe2e90dda to your computer and use it in GitHub Desktop.
Semaphore demo
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