首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 線程使用入門:Timer、Swing Timer 與 Thread 實戰

     編輯:Java 相關知識

Java 平台天生多線程:主程序運行時,垃圾回收、事件處理等在後台線程執行。開發者可利用多線程處理並發任務,主要工具類包括:

  • java.util.Timer:通用定時任務
  • javax.swing.Timer:Swing 專用,事件分發線程執行
  • Thread 類與 Runnable 接口:完全控制

1. java.util.Timer:簡單重複任務

適用於固定頻率執行的輕量任務。任務定義在 TimerTask.run() 中:

import java.util.*;
public class Hi {
    public static void main(String[] args) throws Exception {
        TimerTask task = new TimerTask() {
            public void run() { System.out.println("Hi"); }
        };
        Timer timer = new Timer();
        timer.schedule(task, 0, 500); // 0 延遲,每 500ms 執行
        System.out.println("Press ENTER to stop");
        System.in.read(new byte[10]);
        timer.cancel(); // 取消定時器,程序退出
    }
}

關鍵點:JRE 只要有非守護線程運行就不退出;Timer 默認創建非守護線程,cancel() 後無其他線程則程序結束。

2. javax.swing.Timer:Swing 安全更新 UI

Swing 非線程安全,所有組件操作必須在事件分發線程(EDT)執行。javax.swing.Timer 的監聽器自動在 EDT 運行:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Count {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel label = new JLabel("", JLabel.CENTER);
        label.setFont(new Font("Serif", Font.PLAIN, 36));
        frame.getContentPane().add(label, BorderLayout.CENTER);

        ActionListener listener = new ActionListener() {
            int count = 0;
            public void actionPerformed(ActionEvent e) {
                label.setText(String.valueOf(++count)); // 安全更新 UI
            }
        };
        new Timer(500, listener).start(); // 每 500ms 觸發
        frame.setSize(300, 100);
        frame.setVisible(true);
    }
}

計數器演示

3. Thread / Runnable:長耗時任務與完全控制

兩種方式:繼承 Thread 重寫 run(),或實現 Runnable 傳給 Thread 構造器。後者更靈活,避免繼承限制。

import java.io.*;
import java.net.*;
public class Both {
    public static void main(String[] args) {
        final String url = args[0];
        final String msg = args[1];

        // 方式一:匿名 Thread 子類 - 下載網頁統計字符數
        Thread t1 = new Thread() {
            public void run() {
                try {
                    URL u = new URL(url);
                    BufferedReader r = new BufferedReader(
                        new InputStreamReader(u.openConnection().getInputStream()));
                    int cnt = 0; while (r.read() != -1) cnt++;
                    System.out.println("Size is: " + cnt);
                    r.close();
                } catch (Exception e) { e.printStackTrace(); }
            }
        };
        t1.start();

        // 方式二:Runnable - 定期打印消息
        Runnable r = () -> {
            while (true) {
                System.out.println(msg);
                try { Thread.sleep(500); } catch (InterruptedException ignored) {}
            }
        };
        new Thread(r).start();

        // 主線程等待用戶輸入退出
        try {
            System.out.println("Press ENTER to stop");
            System.in.read(new byte[10]);
        } catch (IOException ignored) {}
        System.exit(0);
    }
}

選擇建議

  • 簡單週期性任務 → java.util.Timer
  • 需更新 Swing UI 的週期任務 → javax.swing.Timer
  • 長運行、阻塞 I/O、需精細控制 → Thread + Runnable
  • 現代項目優先考慮 ExecutorService、ScheduledExecutorService、CompletableFuture。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved