我正在尝试用java创建一个程序,其中线程是可观察的对象,窗口是观察者。我不明白的是如何在更新方法上区分几个线程,它们都做同样的事情,以便我可以单独更新它们在窗口上的位置。
最佳答案
正如 @PeterLawrey 的评论中所述,您可以使用 Thread 中的 name 参数。对象设置一个唯一的名称,然后查询您的线程并查找哪个线程正在做什么。构造函数如下:
public Thread(String name)
Allocates a new Thread object. This constructor has the same effect as Thread (null, null, name).
Parameters:
name - the name of the new thread
但是,为了在执行后更轻松地访问线程并进行跟踪,我建议使用 ThreadGroup目的。来自 API 文档:
A thread group represents a set of threads. In addition, a thread group can also include other thread groups. The thread groups form a tree in which every thread group except the initial thread group has a parent.
因此,可以使用public int enumerate(Thread[] list, boolean recurse)的方法
哪个
Copies into the specified array every active thread in this thread group. If recurse is true, this method recursively enumerates all subgroups of this thread group and references to every active thread in these subgroups are also included. If the array is too short to hold all the threads, the extra threads are silently ignored.
以及组中所有线程的getName()
。我希望它有帮助。干杯
关于java - 如何观察多个可观察线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13218704/