java-建立一個執行緒,在控制檯不斷輸出當前時間,精確到時分秒,每隔一秒輸出一次。
阿新 • • 發佈:2019-02-09
對其實現的一個方法是:
採用繼承Thread類 重寫run方法。
import java.text.SimpleDateFormat; import java.util.Date; /** * 建立一個執行緒,在控制檯不斷輸出當前時間,精確到時分秒,每隔一秒輸出一次。 * * @author 三一 * * @time 2018-7-18 * */ public class test { public static void main(String[] args) { Thread thread = new MyThread(); thread.start(); } } // 通過繼承Thread類 來重寫run方法 class MyThread extends Thread { //通過正則式來設定輸出的時間格式 SimpleDateFormat s = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); //重寫run()方法 public void run() { while (true) { String str = s.format(new Date()); System.out.println(str); try { //間隔時間1秒 Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }