我想要做2個類,DVDPlayer和HomeTheaterFecade, DVDPlayer類裏面有Play().Pause(),Resume()和Stop()方法,從HomeTheaterFecade裏的主函數調用Play() 並開始計時,從主函數調用Pause()計時暫停,Resume() 繼續播放,調用Stop()計時停止。不太會用timer,請教下 謝謝了,請不要粘別人的答案 謝謝。。
何不使用線程?
一些說明我已經寫在註釋中了
public class Test implements Runnable {
//定義一個線程
Thread thread;
//用於停止線程的標誌
private boolean flag=true;
public Test(){
thread=new Thread(this);
}
//因爲該類實現了Runnable,就必須有run方法,當線程啓動時,會調用這個run方法
public void run(){
//獲得當前的時間,毫秒爲單位
long beginTime=System.currentTimeMillis();
//定義已過去的時間
long time=0;
while(flag){
//這裏寫實現計時的代碼
//在這裏,獲得已過去的時間
time=System.currentTimeMillis()-beginTime;
System.out.println("已過"+time+"毫秒");
//暫停線程1秒鐘,不暫停的話可以把下面代碼去掉
try{
Thread.sleep(1000);
}catch(InterruptedException e1){
e1.printStackTrace();
}
}
}
//這裏是啓動線程的方法,也就是啓動線程
public void start(){
thread.start();
}
//這裏是暫停的方法,暫停線程
public void Pause(){
try{
thread.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
//這裏是繼續的方法,喚醒線程
public void Resume(){
thread.notifyAll();
}
//停止線程
public void stop(){
//把flag設成false,則在run中的while循環就會停止循環
flag=false;
}
public static void main(String []args){
//用於測試
Test t=new Test();
//開始線程
t.start();
try{
//10000毫秒以後結束線程
Thread.sleep(10000);
}catch(InterruptedException e1){
e1.printStackTrace();
}
//結束線程
t.stop();
}
}