2 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超7個(gè)贊
下面是一個(gè)使用倒計(jì)時(shí)批處理的示例。
package chapter13;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class BST {
public static void main(String[] args) throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final ExecutorService executorService = Executors.newCachedThreadPool();
Runnable runnableA = () -> {
System.out.println("Runnable A");
latch.countDown();
System.out.println("Runnable A finished");
};
Runnable runnableB = () -> {
System.out.println("Runnable B");
executorService.submit(runnableA);
try {
System.out.println("Runnable B waiting for A to complete");
latch.await();
System.out.println("Runnable B finished");
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
Thread.currentThread().interrupt();
}
};
executorService.submit(runnableB);
Thread.sleep(10);
shutDown(executorService);
}
private static void shutDown(ExecutorService executorService) {
executorService.shutdown();
try {
if (!executorService.awaitTermination(1, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException e) {
executorService.shutdownNow();
}
}
}
我使用方法使主線(xiàn)程休眠,因?yàn)樵谔峤蝗蝿?wù) B 后立即關(guān)閉池可能會(huì)導(dǎo)致池在任務(wù) B 提交任務(wù) A 之前停止接受新任務(wù)。Thread.sleep()

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超3個(gè)贊
一種方法是使用java鎖定方法。例如:
private AtomicBoolean processed = new AtomicBoolean(true) ;
private String result = null ;
public String doAndWait()
{
synchronized(processed) {
doSomethingAsync() ;
processed.wait();
}
return result ;
}
public void doSomethingAsync()
{
...
result="OK";
synchronized(processed) {
processed.notify();
}
}
添加回答
舉報(bào)