import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Demo1 {
public static void main(String[] args) {
ThreadPoolExecutor thread = new ThreadPoolExecutor(
5,
5,
5,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(10),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);
RunnableA runnableA = new RunnableA();
thread.submit(runnableA);
thread.submit(runnableA);
thread.shutdown();
}
}
import java.util.concurrent.locks.ReentrantLock;
public class RunnableA implements Runnable {
private static final ReentrantLock LOCK = new ReentrantLock();
private static int number = 0;
@Override
public void run() {
while (true) {
LOCK.lock();
try {
if (number == 100) {
break;
}
String name = Thread.currentThread().getName();
if (number % 2 == 0) {
if ("pool-1-thread-1".equals(name)) {
System.out.println("我是" + name + "线程,我打印奇数" + ++number);
}
} else {
if ("pool-1-thread-2".equals(name)) {
System.out.println("我是" + name + "线程,我打印偶数" + ++number);
}
}
} finally {
LOCK.unlock();
}
}
}
}