Commit 018061d2 authored by yihua.huang's avatar yihua.huang

fix error in thread pool

parent cdc423f2
...@@ -2,6 +2,7 @@ package us.codecraft.webmagic.selector.thread; ...@@ -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 { ...@@ -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 { ...@@ -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,24 +44,41 @@ public class ThreadPool { ...@@ -43,24 +44,41 @@ public class ThreadPool {
private ExecutorService executorService; private ExecutorService executorService;
public void execute(Runnable runnable) { public void execute(final Runnable runnable) {
try { try {
if (threadAlive.get() >= threadNum) {
reentrantLock.lock(); reentrantLock.lock();
while (threadAlive >= threadNum) { while (threadAlive.get() >= threadNum) {
try { try {
condition.await(); condition.await();
} catch (InterruptedException e) { } catch (InterruptedException e) {
} }
} }
threadAlive++; }
System.out.println(threadAlive); threadAlive.incrementAndGet();
executorService.execute(runnable); executorService.execute(new Runnable() {
@Override
public void run() {
try {
runnable.run();
} finally { } finally {
threadAlive--; try {
reentrantLock.lock();
threadAlive.decrementAndGet();
condition.signal(); condition.signal();
} finally {
reentrantLock.unlock(); reentrantLock.unlock();
} }
} }
}
});
} finally {
if (reentrantLock.isLocked()) {
reentrantLock.unlock();
}
}
}
public boolean isShutdown() { public boolean isShutdown() {
return executorService.isShutdown(); return executorService.isShutdown();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment