Thread creation and starting
This question already has an answer here:
In general you should not extend Thread
, but implement Runnable
instead. Your example would then become:
class MyRunnable implements Runnable {
public void run() {
// Whatever needs to be done.
}
}
MyRunnable obj = new MyRunnable();
Thread t = new Thread(obj);
t.start()
Yes, there is a difference: you should not extend Thread
, but use new Thread(myRunnable)
. This is similar to your first approach, only your way is misguided in extending Thread instead of implementing Runnable. So do this:
class MyRunnable implements Runnable {
public void run() { ... }
}
Thread t = new MyThread(new MyRunnable());
t.start();
or, more conveniently,
new Thread(new Runnable() { public void run() {
... stuff ...
}}).start();
Be sure to distinguish the concepts of Thread
and Runnable
: the former is a heavy-weight handle to an actual system resource; the latter is just a holder of a method.
Thread t = new Thread(obj);
takes a Runnable obj
- the recommended way.
MyThread obj = new MyThread();
requires you to extend
Thread
which is considered inadvisable nowadays.
See "implements Runnable" vs. "extends Thread" for details on the debate.
链接地址: http://www.djcxy.com/p/92078.html上一篇: MyThread类更好的技术
下一篇: 线程创建和启动