日期:2014-05-20 浏览次数:20757 次
package com.demo.service.include.impl;
import java.util.concurrent.CountDownLatch;
public class A implements Runnable{
CountDownLatch latch;//同步辅助类
private String flag;
public CountDownLatch getLatch() {
return latch;
}
public void setLatch(CountDownLatch latch) {
this.latch = latch;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
@Override
public void run() {
try{
setFlag("B");
throw new Exception();
}catch(Exception e){
setFlag("A");
}finally{
latch.countDown();
}
}
}
package com.demo.service.include.impl;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class B {
public static void main(String[] args) throws InterruptedException {
ExecutorService t=Executors.newCachedThreadPool();
CountDownLatch latch=new CountDownLatch(1);
A a=new A();
a.setLatch(latch);
t.execute(a);
latch.await();
System.out.println(a.getFlag());
}
}
Runnable getTask() {
for (;;) {
try {
int state = runState;
if (state > SHUTDOWN)
return null;
Runnable r;
if (state == SHUTDOWN) // Help drain queue
r = workQueue.poll();
else if (poolSize > corePoolSize
------解决方案--------------------
allowCoreThreadTimeOut)
r = workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS);
else
r = workQueue.take();
if (r != null)
return r;
if (workerCanExit()) {
if (runState >= SHUTDOWN) // Wake up others
interruptIdleWorkers();
return null;
}
// Else retry
} catch (InterruptedException ie) {
// On interruption, re-check runState
}
}
}