参考Java线程的6种状态及切换(透彻讲解)
线程池参数 老八股文了。俩个时间参数是 线程空闲回收时间,回收时候用的。
execute 提交时候的流程 老八股文了。
线程回收条件
while (task != null || (task = getTask()) != null) {
//task 为null 会去 拿线程执行,拿不到就回收。
}
拿不到的条件。
1、队列空。线程池停了等情况
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
2、 (工作线程大于最小线程 || 超过空闲时间)&&(工作线程大于1 || 队列空)
工作线程大于1 是应为自己停了怎么也得有个在运行的,队列空就不需要了
int wc = workerCountOf(c);
// Are workers subject to culling?
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
笔试题
ab俩个线程交替打印,
可以取个巧直接用synchronized wait notifyAll
Object o = new Object();
AtomicInteger count = new AtomicInteger(0);
new Thread(new P("a", o, count),"aaa").start();
new Thread(new P("b", o, count),"bbb").start();
static class P implements Runnable{
String info;
final Object lock;
AtomicInteger count;
public P(String info, Object lock, AtomicInteger count) {
//省略
}
@SneakyThrows
@Override
public void run() {
synchronized (lock){
while (this.count.get() < 20){
log.info(info + "" +count.incrementAndGet());
lock.notifyAll();
// lock.wait();
lock.wait(1000*20);
log.info("100毫秒");
}
}
}
}
三个线程交替打印
用ReentrantLock的Condition
public static void main(String[] args){
AtomicInteger count = new AtomicInteger(0);
ReentrantLock lock = new ReentrantLock();
// 声明互相等待的条件
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
Condition condition3 = lock.newCondition();
new Thread(new P2(lock,condition1,condition2,"a", count),"aaa").start();
new Thread(new P2(lock,condition2,condition3,"b", count),"bbb").start();
new Thread(new P2(lock,condition3,condition1,"c", count),"ccc").start();
lock.lock();
condition1.signal();
lock.unlock();
}
static class P2 implements Runnable{
public P2(ReentrantLock lock,Condition condition, Condition conditionNext, String info, AtomicInteger count) {
this.lock = lock;
this.condition = condition;
this.conditionNext = conditionNext;
this.info = info;
this.count = count;
}
ReentrantLock lock;
Condition condition;
Condition conditionNext;
String info;
AtomicInteger count;
@SneakyThrows
@Override
public void run() {
while (this.count.get() < 20) {
lock.lock();
condition.await();
log.info(info + "" + count.incrementAndGet());
conditionNext.signal();
lock.unlock();
}
}
}



