Skip to content

Instantly share code, notes, and snippets.

@haitaoyao
Created March 14, 2013 03:33
Show Gist options
  • Save haitaoyao/5158607 to your computer and use it in GitHub Desktop.
Save haitaoyao/5158607 to your computer and use it in GitHub Desktop.
测试SynchronousQueue和ArrayBlockingQueue情况下, ThreadPoolExecutor的不同表现.
import static org.junit.Assert.assertEquals;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
public class ThreadPoolTest {
@Test
public void testThreadPool() {
int threadCount = 10;
ThreadPoolExecutor aThreadPool = new ThreadPoolExecutor(threadCount,
20, 5, TimeUnit.MINUTES, new SynchronousQueue<Runnable>());
ThreadPoolExecutor bThreadPool = new ThreadPoolExecutor(threadCount,
20, 5, TimeUnit.MINUTES, new ArrayBlockingQueue<Runnable>(
threadCount));
Semaphore aSemaphore = this.runThreadPool(aThreadPool, threadCount,
"aThreadPool");
assertEquals(0, aSemaphore.availablePermits());
System.out.println("---------------------------------------");
Semaphore bSemaphore = this.runThreadPool(bThreadPool, threadCount,
"bThreadPool");
assertEquals(1, bSemaphore.availablePermits());
}
private Semaphore runThreadPool(ThreadPoolExecutor threadPool,
int threadCount, String name) {
int max = threadCount + 1;
Semaphore semaphore = new Semaphore(max);
while (max-- > 0) {
threadPool.submit(new Worker(name + "--" + max, semaphore));
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
threadPool.shutdownNow();
return semaphore;
}
static class Worker implements Runnable {
private final String name;
private final Semaphore semaphore;
public Worker(String name, Semaphore latch) {
super();
this.name = name;
this.semaphore = latch;
}
@Override
public void run() {
System.out.println(this.name + " is running");
try {
this.semaphore.acquire();
Thread.sleep(100000);
} catch (InterruptedException e) {
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment