Skip to content

Instantly share code, notes, and snippets.

@zheltkov
Created February 10, 2015 18:07
Show Gist options
  • Save zheltkov/83d0a8ab6be9e9fecf3e to your computer and use it in GitHub Desktop.
Save zheltkov/83d0a8ab6be9e9fecf3e to your computer and use it in GitHub Desktop.
thread pool that wait
package com.company;
import java.util.concurrent.*;
public class Main {
private static ThreadPoolExecutor threadPoolExecutor;
public static void main(String[] args) {
// write your code here
threadPoolExecutor = new MyThreadPoolExecutor();
threadPoolExecutor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (e instanceof MyThreadPoolExecutor) {
MyThreadPoolExecutor myThreadPoolExecutor = (MyThreadPoolExecutor) e;
myThreadPoolExecutor.waitFirstComplite();
myThreadPoolExecutor.execute(r);
}
}
});
for (int i = 0; i < 100; i++) {
System.out.println("execute " + i);
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000L);
System.out.println("finish " + this);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
System.out.println("core pool size before = " + threadPoolExecutor.getPoolSize());
System.out.println("queue size = " + threadPoolExecutor.getQueue().size());
System.out.println("===================================");
try {
Thread.sleep(20000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("===================================");
System.out.println("core pool size after = " + threadPoolExecutor.getPoolSize());
System.out.println("queue size = " + threadPoolExecutor.getQueue().size());
for (int i = 0; i < 100; i++) {
System.out.println("execute " + i);
final int finalI = i;
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(finalI * 500L);
System.out.println("finish " + this);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
threadPoolExecutor.shutdown();
}
private static class MyThreadPoolExecutor extends ThreadPoolExecutor {
private Object monitor = new Object();
public MyThreadPoolExecutor() {
super(10, 30, 10L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(true));
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
System.out.println("done!!!");
synchronized (monitor) {
monitor.notifyAll();
}
}
public void waitFirstComplite() {
System.out.println("wait first complete...");
synchronized (monitor) {
try {
monitor.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment