在我的学校的多线程问题和练习的程序解决方案中,实现Runnable
接口的类通常被赋予一个Thread
字段,该字段在下面的示例中自动实例化:
protected Thread thr = new Thread(this);
此字段随后用作控制Thread的方法,类本身在该Thread上被实例化。例如:
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
的线程?
发布于 2018-06-10 00:50:45
这是如何工作的?
Thread
构造函数接受一个Runnable
,Thread
实现这个接口。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
}
https://stackoverflow.com/questions/50776368
复制相似问题