Java 线程倒计时
Java Countdown with thread
我在java中写了一个class作为倒计时时钟。我的 class 看起来像这样:
public class CountDown implements Runnable {
...
@Override
public void run() {
// The functionality of the clock.
}
...
}
现在,当我想 运行 另一个 class 的倒计时时,我使用此代码
(new Thread(new CountDown(10))).start;
我的问题是:
如果我把class改成这样会不会更好:
public class CountDown {
...
public void start() {
new Thread(new Runnable(){
@Override
public void run(){
// The functionality of the clock.
}
).start();
}
...
}
然后像这样从另一个 class 调用它:
new CountDown(10).start();
我相信您的第一个代码片段是首选解决方案,因为您没有致力于特定的实现。 Thread
is not the only implementation of Runnable
(e.g. TimerTask
, FutureTask
,等等)。
通过让您的 CountDown
在实施中使用 Thread
,您可以从使用您的 CountDown
的任何人那里夺走大量控制权。参见 "implements Runnable" vs. "extends Thread"
我在java中写了一个class作为倒计时时钟。我的 class 看起来像这样:
public class CountDown implements Runnable {
...
@Override
public void run() {
// The functionality of the clock.
}
...
}
现在,当我想 运行 另一个 class 的倒计时时,我使用此代码
(new Thread(new CountDown(10))).start;
我的问题是:
如果我把class改成这样会不会更好:
public class CountDown {
...
public void start() {
new Thread(new Runnable(){
@Override
public void run(){
// The functionality of the clock.
}
).start();
}
...
}
然后像这样从另一个 class 调用它:
new CountDown(10).start();
我相信您的第一个代码片段是首选解决方案,因为您没有致力于特定的实现。 Thread
is not the only implementation of Runnable
(e.g. TimerTask
, FutureTask
,等等)。
通过让您的 CountDown
在实施中使用 Thread
,您可以从使用您的 CountDown
的任何人那里夺走大量控制权。参见 "implements Runnable" vs. "extends Thread"