Skip to content

Instantly share code, notes, and snippets.

@zavakid
Created October 12, 2012 13:12
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 zavakid/3879133 to your computer and use it in GitHub Desktop.
Save zavakid/3879133 to your computer and use it in GitHub Desktop.
Semaphore hold the thread
package com.zavakid.concurrent;
import java.util.concurrent.Semaphore;
import org.junit.Test;
/**
* @author Zava 2012-10-12 下午1:06:15
* @version 1.0
*/
public class SemaphoreTest {
private final Semaphore sempahore = new Semaphore(5);
@Test
public void test() throws InterruptedException {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("thread1 started acquire 4 ");
sempahore.acquire(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread1 has acquired 4, done...");
}
});
thread1.start();
thread1.join();
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("thread2 started acquire 1");
sempahore.acquire(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread2 has acquired 1, done...");
}
});
thread2.start();
thread2.join();
Thread thread3 = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("thread3 started acquire 2");
sempahore.acquire(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread3 has acquired 2, done...");
}
}, "thread-3");
thread3.start();
System.out.println("sleep 1s");
Thread.sleep(1000);
System.out.println("wake up now");
Thread thread4 = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("thread4 started acquire 1");
sempahore.acquire(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread4 has acquired 1, done...");
}
}, "thread-4");
thread4.start();
System.out.println("sleep 1s");
Thread.sleep(1000);
System.out.println("wake up now");
Thread thread5 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread5 started release 1");
sempahore.release(1);
System.out.println("thread5 has release 1, done...");
}
}, "thread-5");
thread5.start();
thread3.join();
thread4.join();
System.out.println("all done, but never reach here...");
}
}
@zavakid
Copy link
Author

zavakid commented Oct 12, 2012

this code is needed @ http://www.zavakid.com/207

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment