您可以将每个线程的引用及其 id 或 Name 作为键存储到 HashMap 中。稍后,当您想要处理某个特定的 Cashier 线程时,请使用 Name 或 id 从 HashMap 中获取相应的 Thread 并调用相应的其上的 logOff() 方法。
You can store each thread's reference into a HashMap - along with its id or Name as the key. Later when you want to deal with one particular Cashier thread , use the Name or id to fetch the corresponding Thread from the HashMap and call the appropriate logOff() method on it.
如果收集对所有线程的引用是一个问题,另一种方法可能是使用一个公共静态同步 HashMap,该 HashMap 将 threadId(在运行时分配给每个线程的随机数)作为键,将布尔值作为值。您可以修改 while 循环以从此集中式 Map 中选取相应的布尔值。这可以让您注销特定的收银员。
If collecting the reference to all the threads is a problem, One other way could be having a public static synchronized HashMap that has the threadId(random number assigned at runtime to each thread) as the key and the boolean as the value. You can modify the while loop to pick the corresponding boolean value from this centralized Map. This would let you log-off a particular cashier.
发布评论
评论(4)
现在,使用内置中断标志而不是布尔属性:
当您想通过单击按钮来关闭线程时,只需调用:
当然您需要从客户端代码访问
t
变量。Now instead of a boolean property use built-in interrupted flag:
When you want to turn of the thread by clicking on a button simply call:
Of course you need to have access to
t
variable from the client code.您可以将每个线程的引用及其
id
或Name
作为键存储到HashMap
中。稍后,当您想要处理某个特定的 Cashier 线程时,请使用Name
或id
从 HashMap 中获取相应的Thread
并调用相应的其上的logOff()
方法。You can store each thread's reference into a
HashMap
- along with itsid
orName
as the key. Later when you want to deal with one particular Cashier thread , use theName
orid
to fetch the correspondingThread
from the HashMap and call the appropriatelogOff()
method on it.如果收集对所有线程的引用是一个问题,另一种方法可能是使用一个公共静态同步 HashMap,该 HashMap 将 threadId(在运行时分配给每个线程的随机数)作为键,将布尔值作为值。您可以修改 while 循环以从此集中式 Map 中选取相应的布尔值。这可以让您注销特定的收银员。
If collecting the reference to all the threads is a problem, One other way could be having a public static synchronized HashMap that has the threadId(random number assigned at runtime to each thread) as the key and the boolean as the value. You can modify the while loop to pick the corresponding boolean value from this centralized Map. This would let you log-off a particular cashier.
您可以在某处保留 Thread 对象的引用,以便您可以调用 threadObj.logOff()
如果您不愿意这样做,那么在创建线程时您可以为线程分配一个唯一的名称。
在运行时,您可以通过以下方式获取线程:
我仍然建议您将线程对象存储在哈希映射中,而不是在运行时枚举它们。
You can keep a reference of the Thread object somewhere so that u can call threadObj.logOff()
If you are not willing to do that then while creating a thred u can assign a unique name to the thread.
At runtime, u can get the thread by:
I'll still suggest that u store the thread objects in a hash map instead of enumerating them at runtime.