简体   繁体   English

如何引用线程,以及如何在ThreadLocal上进行验证

[英]How to a reference of a thread, and verification on ThreadLocal

I'm looking for verification on the following use of ThreadLocal . 我正在寻找有关ThreadLocal的以下用法的验证。

I have a service, say ServiceA running on a set of processes, say processSetX in the system. 我有一项服务,例如在一组进程上运行的ServiceA ,例如系统中的processSetX Which processSetX will be on ServiceA isn't known until runtime and may vary. 直到运行时才知道哪个processSetX将在ServiceA上使用,并且可能会有所不同。 The processes in processSetX may run on different threads. processSetX的进程可以在不同的线程上运行。 ServiceA has to recognize all processes in processSetX the same way. ServiceA必须以相同的方式识别processSetX的所有进程。

For this, I'm supposed to write an ID value, say, of type String, to thread local storage (TLS) of a new thread and read this value later on when needed. 为此,我应该将一个ID值(例如String类型)写入新线程的线程本地存储(TLS),并在以后需要时读取此值。 So, the ID of the first thread invoking ServiceA will be this ID for ServiceA to recognize them all. 因此,调用ServiceA的第一个线程的ID将是此ID,以便ServiceA可以识别所有线程。 When this first thread starts another thread, it'll go onto this new thread's TLS and write this ID. 当第一个线程启动另一个线程时,它将进入该新线程的TLS并写入此ID。 From there on, every thread in this chain will pass this ID to the new one. 从那里开始,该链中的每个线程都会将此ID传递给新的ID。

I'm looking to verify ThreadLocal is the way to work this. 我想验证ThreadLocal是解决此问题的方法。

I haven't used it before - I want to make sure. 我以前没用过-我想确定。

TIA. TIA。

//================== // ==================

EDIT: 编辑:

is there a way to get the calling thread's reference? 有没有一种方法来获取调用线程的引用?

eg.: 例如。:

a thread, say threadX is making a call to, say methodA() . 一个线程,例如threadX正在调用一个方法,例如threadX methodA() is there a way for methodA() to know "who" is calling it? 有没有办法让methodA()知道“谁”正在调用它? if so - methodA() is able to invoke a getter method of threadX to read a value from its thread-local storage. 如果是这样,则methodA()能够调用threadX的getter方法从其线程本地存储中读取值。

TIA TIA

//================= // =================

EDIT-2: 编辑2:

Thread.currentThread() returns something like Thread[main,5,main] . Thread.currentThread()返回类似Thread[main,5,main] this may collide across threads. 这可能会在线程之间发生冲突。

I think at first, you just need a normal member variable. 我认为起初,您只需要一个普通的成员变量。

For example: 例如:

// Thread
public class CalledThread extends Thread {

    public String myId;

    public void run() {
    ....

// Caller
    CalledThread t = new CalledThread();
    t.myId = "the thread ID";
    t.start();

However, you won't be able to access myId once you start calling your service classes, so for that you could use a ThreadLocal . 但是,一旦开始调用服务类,您将无法访问myId ,因此您可以使用ThreadLocal

In CalledThread assign the myId to your ThreadLocal in run . CalledThread分配myId到你ThreadLocalrun

threadLocal.set(myId)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM