java - 实现 Runnable 的类中的 Thread 字段,它实例化所述类

标签 java multithreading runnable

在我校的多线程问题和习题的程序解答中,实现Runnable接口(interface)的类通常会被赋予一个Thread字段,在下面的例子中会自动实例化:

protected Thread thr = new Thread(this);

此字段随后用作控制类本身实例化的线程的方法。例如:

public void stop() {
    if (thr != null) thr.interrupt();
}

然后用于中断使用 Runnable 类创建的 Thread 对象。

下面给出了直接从上述解决方案移植而来的完整类示例:

package hokej;
import java.awt.Color;
public abstract class AktFigura extends Figura implements Runnable {
    protected Thread nit = new Thread(this);
    private int tAzur;
    private boolean radi;
    public AktFigura(Scena s, int xx, int yy,
    Color b, int t) {
        super(s, xx, yy, b); tAzur = t;
    }
    protected abstract void azurirajPolozaj();
   public void run() {
   try {
       while (!Thread.interrupted()) {
           synchronized (this) {
                if (!radi) wait();
           }
           azurirajPolozaj();
           scena.repaint();
           Thread.sleep(tAzur);
       }
   } catch (InterruptedException ie) {}
   }
   public synchronized void kreni() {
       radi = true; notify();
   }
   public void stani() { radi = false; }
   public void prekini() {
       if (nit != null) nit.interrupt();
   }
}

我的问题是:这是如何工作的?
Thread 字段不应该是一个独立的对象,与通过调用 new Thread(class); 在程序的其他部分生成的对象不同(因此关键字的名称 - )?
或者这只是 Java 解释器以某种方式识别的一种特殊情况?

另一个问题是这种设计作为控制方法的可行性。是否有任何更简单/更有效的替代方法来控制 Runnable 的线程?

最佳答案

How does this work?

Thread构造函数接受一个RunnableThread实现了这个接口(interface)。 this 指的是一个Thread 实例。因此,语句 Thread thr = new Thread(this) 是有效的,但应避免这种做法。

Is there any simpler/more efficient alternative for controlling a Runnable's thread?

Thread thread = new Thread(new AktFiguraImpl());
thread.start();

您可以通过专门为此目的设计的类来控制线程。

class ThreadController {
    public ThreadController(Thread thread, AktFigura figura) { ... }

    // methods to manipulate the thread
}

关于java - 实现 Runnable 的类中的 Thread 字段,它实例化所述类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50776368/

相关文章:

时间尺度表示的不同类型数据的Java数据结构设计

java - 在 java swing 中绘制 JComponent 的更好方法

java - 在 IntelliJ 或其他 IDE 中获取完整的 JDK 源代码

java - PipedInputStream - 如何避免 "java.io.IOException: Pipe broken"

java - 如何从java中的线程传播异常?

java - 添加属性文件以构建可运行 jar 的路径

java - 错误: More than one file was found with OS independent path 'META-INF/LICENSE'

c# - 使用多个 http 请求-响应

java - 可运行的问题

java - 我如何使用 wait/notifyAll