如何在Java中获取线程ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24005344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 09:39:15  来源:igfitidea点击:

How to get thread ID in Java

javamultithreading

提问by riship89

I can specify log4j formatter as follows to print current thread id in spring mvc application

我可以按如下方式指定 log4j 格式化程序以在 spring mvc 应用程序中打印当前线程 ID

log4j.appender.FILE.layout.ConversionPattern=%d{ISO8601} %p %t %c - %m%n

How do I programmatically get current thread id in my spring application. More precisely, I want to get current thread id in an aspect that intercepts controller methods. My aspect is as follows:

如何以编程方式获取 Spring 应用程序中的当前线程 ID。更准确地说,我想在拦截控制器方法的方面获取当前线程 ID。我的方面如下:

@Configurable
@Aspect
public class TimingAspect {

    @Autowired
    private HttpServletRequest httpServletRequest;

    //Generic performance logger for any mothod
    private Object logPerfomanceInfo(ProceedingJoinPoint joinPoint) {
       // do something with thread id
       // do something with httprequest
        ...
    }

    // Performance info for API calls
    @Around("execution(* package.controller.*.*(..))")
    public Object logAroundApis(ProceedingJoinPoint joinPoint) throws Throwable {
        return logPerfomanceInfo(joinPoint);
    }
}

采纳答案by kriegaex

I hope I understand your question correctly and this is what you're looking for:

我希望我能正确理解你的问题,这就是你要找的:

Thread.currentThread().getId()