Java21 和 Java25 中获取虚拟线程挂载的平台线程
Java juc About 845 words反射
需在虚拟线程中调用invoke方法,返回的是ForkJoinWorkerThread。
通过ForkJoinWorkerThread还是获取对应的ForkJoinPool。
Class<Thread> threadClass = Thread.class;
Method method = threadClass.getDeclaredMethod("currentCarrierThread");
method.setAccessible(true);
// 返回的 object 对象即为平台线程
Object object = method.invoke(null)
ForkJoinWorkerThread forkJoinWorkerThread = (ForkJoinWorkerThread) object;
ForkJoinPool pool = forkJoinWorkerThread.getPool();
Thread 源码
currentCarrierThread方法没有对外公开,所以只能使用反射调用,获取虚拟线程挂载的载体线程。
public class Thread implements Runnable {
/**
* Returns the Thread object for the current platform thread. If the
* current thread is a virtual thread then this method returns the carrier.
*/
@IntrinsicCandidate
static native Thread currentCarrierThread();
}
注意
需要添加启动参数,否则反射调用时会报错。
--add-opens java.base/java.lang=ALL-UNNAMED
Views: 7 · Posted: 2025-12-26
———         Thanks for Reading         ———
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...