Created
July 17, 2020 06:23
-
-
Save cmonkey/f9f8b0cbe5b8480009c074c403fc8984 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 java.util.concurrent.Executors; | |
import java.util.concurrent.Callable; | |
import java.util.List; | |
import java.util.concurrent.CompletableFuture; | |
import java.time.Instant; | |
import java.util.concurrent.TimeUnit; | |
public class LoomApp{ | |
public static void main (String [] args) throws Exception{ | |
var thread = Thread.startVirtualThread(() -> System.out.println("virtualthread Hello")); | |
thread.join(); | |
var thread1 = Thread.builder().virtual().task(() -> System.out.println("virtual task hello")).build(); | |
var thread2 = Thread.builder() | |
.virtual() | |
.name("bob") | |
.task(() -> System.out.println("virtual name task I'm Bob!")) | |
.start(); | |
var factory = Thread.builder().virtual().name("worker", 0).factory(); | |
try(var executor = Executors.newVirtualThreadExecutor()){ | |
executor.execute(() -> System.out.println("Hello")); | |
executor.execute(() -> System.out.println("Hi")); | |
} | |
try(var executor = Executors.newVirtualThreadExecutor()){ | |
Callable<String> task1 = () -> "invokeAny foo"; | |
Callable<String> task2 = () -> "invokeAny bar"; | |
Callable<String> task3 = () -> "invokeAny baz"; | |
var result = executor.invokeAny(List.of(task1, task2, task3)); | |
} | |
try(var executor = Executors.newVirtualThreadExecutor()){ | |
Callable<String> task1 = () -> "completable future foo"; | |
Callable<String> task2 = () -> "completable future bar"; | |
Callable<String> task3 = () -> "completable future baz"; | |
var cfs = executor.submitTasks(List.of(task1, task2, task3)); | |
CompletableFuture.completed(cfs) | |
.map(CompletableFuture::join) | |
.forEach(System.out::println); | |
} | |
var seconds = 3; | |
var deadline = Instant.now().plusSeconds(seconds) ; | |
try(var executor = Executors.newVirtualThreadExecutor().withDeadline(deadline)){ | |
Callable<String> task1 = () -> "deadline foo"; | |
Callable<String> task2 = () -> "deadline bar"; | |
Callable<String> task3 = () -> "deadline baz"; | |
Callable<String> task4 = () -> { | |
var sleepSeconds = seconds - 1; | |
TimeUnit.SECONDS.sleep(sleepSeconds); | |
return "deadline task4 by sleep " + sleepSeconds + " seconds"; | |
}; | |
var cfs = executor.submitTasks(List.of(task1, task2, task3, task4)); | |
CompletableFuture.completed(cfs) | |
.map(CompletableFuture::join) | |
.forEach(System.out::println); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ref:
https://cmonkey.github.io/2020/07/17/loom/
https://wiki.openjdk.java.net/display/loom/Getting+started