java - 如何观察多个可观察线程

标签 java multithreading observer-pattern observable

我正在尝试用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/

相关文章:

javascript - 观察 ES6 模块属性

design-patterns - 为什么 Symfony EventDispatcher 对事件使用任意名称而不是基于类的传播?

java - GSON 输出空数组值

java - Spring @asynch 线程并发共享资源

java - 使用单个 hashmap 与多个变量

c++ - 析构函数 vs 成员函数竞赛

Java 方法仅在使用 JavaFX 的调度程序可运行关闭后运行一次完整代码

php - 没有 OOP 的观察者模式逻辑?

java - 为什么即使在 volatile 修复之后仍然不鼓励双重检查锁定?

java - 键盘缓冲区(以字符串作为输入)