【问题标题】:Thread field inside a class that implements Runnable, which instantiates said class实现 Runnable 的类中的 Thread 字段,该类实例化所述类
【发布时间】:2018-06-09 16:34:38
【问题描述】:

在我学校的多线程问题和练习的程序解决方案中,实现Runnable接口的类通常会被赋予一个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); 生成的对象分开的对象吗(因此关键字的名称 - new)?
或者这只是 Java 解释器以某种方式识别的一种特殊情况?

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

【问题讨论】:

标签: java multithreading runnable


【解决方案1】:

这是如何工作的?

Thread 构造函数采用RunnableThread 实现了这个接口。 this 指的是 Thread 实例。所以,Thread thr = new Thread(this) 声明是有效的,但应该避免这种做法。

是否有任何更简单/更有效的替代方法来控制 Runnable 的线程?

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

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

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

    // methods to manipulate the thread
}

【讨论】:

  • 这正是他的讲师的代码正在做的事情,尽管是在一个子类中——他在 Runnable 本身内部的受保护继承字段上调用 ​​nit.start()。 1+
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多