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,22 +44,39 @@ public class ThreadPool { ...@@ -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(); }
} }
} }
......
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