fix error in thread pool
parent
cdc423f2bf
commit
018061d2cd
|
@ -2,6 +2,7 @@ package us.codecraft.webmagic.selector.thread;
|
||||||
|
|
||||||
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
import java.util.concurrent.locks.Condition;
|
import java.util.concurrent.locks.Condition;
|
||||||
import java.util.concurrent.locks.ReentrantLock;
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
|
|
||||||
|
@ -13,7 +14,7 @@ public class ThreadPool {
|
||||||
|
|
||||||
private int threadNum;
|
private int threadNum;
|
||||||
|
|
||||||
private int threadAlive;
|
private AtomicInteger threadAlive = new AtomicInteger();
|
||||||
|
|
||||||
private ReentrantLock reentrantLock = new ReentrantLock();
|
private ReentrantLock reentrantLock = new ReentrantLock();
|
||||||
|
|
||||||
|
@ -34,7 +35,7 @@ public class ThreadPool {
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getThreadAlive() {
|
public int getThreadAlive() {
|
||||||
return threadAlive;
|
return threadAlive.get();
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getThreadNum() {
|
public int getThreadNum() {
|
||||||
|
@ -43,22 +44,39 @@ public class ThreadPool {
|
||||||
|
|
||||||
private ExecutorService executorService;
|
private ExecutorService executorService;
|
||||||
|
|
||||||
public void execute(Runnable runnable) {
|
public void execute(final Runnable runnable) {
|
||||||
try {
|
try {
|
||||||
reentrantLock.lock();
|
|
||||||
while (threadAlive >= threadNum) {
|
if (threadAlive.get() >= threadNum) {
|
||||||
try {
|
reentrantLock.lock();
|
||||||
condition.await();
|
while (threadAlive.get() >= threadNum) {
|
||||||
} catch (InterruptedException e) {
|
try {
|
||||||
|
condition.await();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
threadAlive++;
|
threadAlive.incrementAndGet();
|
||||||
System.out.println(threadAlive);
|
executorService.execute(new Runnable() {
|
||||||
executorService.execute(runnable);
|
@Override
|
||||||
|
public void run() {
|
||||||
|
try {
|
||||||
|
runnable.run();
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
reentrantLock.lock();
|
||||||
|
threadAlive.decrementAndGet();
|
||||||
|
condition.signal();
|
||||||
|
} finally {
|
||||||
|
reentrantLock.unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
} finally {
|
} finally {
|
||||||
threadAlive--;
|
if (reentrantLock.isLocked()) {
|
||||||
condition.signal();
|
reentrantLock.unlock();
|
||||||
reentrantLock.unlock();
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue