Last active
February 13, 2019 03:25
-
-
Save evil0th/d2eb6c6247bd93942a0f9f11fde7a700 to your computer and use it in GitHub Desktop.
多线程测试代码
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.Test; | |
import java.util.concurrent.*; | |
import java.util.function.Supplier; | |
public class ThreadTest { | |
private static final ScheduledExecutorService schedulerExecutor = | |
Executors.newScheduledThreadPool(10); | |
private static final ExecutorService executorService = | |
Executors.newCachedThreadPool(); | |
public static <T> CompletableFuture<T> supplyAsync( | |
final Supplier<T> supplier, long timeoutValue, TimeUnit timeUnit, | |
T defaultValue) { | |
final CompletableFuture<T> cf = new CompletableFuture<T>(); | |
// as pointed out by Peti, the ForkJoinPool.commonPool() delivers a | |
// ForkJoinTask implementation of Future, that doesn't interrupt when cancelling | |
// Using Executors.newCachedThreadPool instead in the example | |
// submit task | |
Future<?> future = executorService.submit(() -> { | |
try { | |
cf.complete(supplier.get()); | |
} catch (Throwable ex) { | |
cf.completeExceptionally(ex); | |
} | |
}); | |
//schedule watcher | |
schedulerExecutor.schedule(() -> { | |
if (!cf.isDone()) { | |
cf.complete(defaultValue); | |
future.cancel(true); | |
} | |
}, timeoutValue, timeUnit); | |
return cf; | |
} | |
/** | |
* 异步超时 | |
* @throws Exception | |
*/ | |
@Test | |
public void syncTimeoutTest() throws Exception { | |
CompletableFuture<String> a = supplyAsync(() -> { | |
try { | |
Thread.sleep(2000); | |
} catch (InterruptedException e1) { | |
e1.printStackTrace(); | |
} | |
return "hi"; | |
}, 1, TimeUnit.SECONDS, "default"); | |
System.out.println(a.get()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment