chap10-4.txt

来自「清华大学出版社经典教材系列」· 文本 代码 · 共 41 行

TXT
41
字号
// 程序10-4
import java.awt.*;
import java.applet.*;
import java.util.Date;		// 获取当前时间
import java.text.DateFormat;	// 将时间转换为一个字符串

public class  clock extends Applet implements Runnable{
    DateFormat  timeFormat;
    Thread  timer;		// 更新时间的线程
    boolean  running;		// 停止线程的运行
    
    public void init( ){
        timeFormat=DateFormat.getDateTimeInstance( ); 	// 日期时间格式
    }
	
    public void start( ){
        running=true;
        if(timer==null){		// 如果还没有启动线程,创建一个时间线程
            timer=new Thread(this);	// 创建线程
            timer.start( );		// 启动线程 
        }
    }
    
    public void run( ){		// 覆盖了接口Runnable中的run方法
        while(running){
            showStatus(timeFormat.format(new Date( )));	// 获取最新日期时间
            try{
                Thread.sleep(1000);		// 睡眠1秒
            }catch(InterruptedException e){ 
                System.exit(0); 
            }
            timer=null;  // 如果线程退出,将其变成垃圾,这样再次调用start方法时,
             // 可以重新创建新线程
        }
    }
    
    public void stop( ){
        running=false; 
        timer.stop( );		// 终止线程 
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?