線程是程序執行的最小單元,也是 CPU 調度的基本單位。每個線程擁有獨立的棧空間,局部變量互不干擾;若多線程同時調用同一方法,各自獲得參數與局部變量的獨立副本。
public class Test extends Thread {
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("hello_" + i);
}
}
}
在 Applet 中啟動:
import java.applet.Applet;
public class TestApplet extends Applet {
public void init() {
Test tt = new Test();
tt.start(); // 啟動新線程,自動調用 run()
}
}
關鍵區別:run() 只是普通方法調用,在當前線程執行;start() 則創建新線程並異步執行 run()。
Java 不支持多重繼承,實現 Runnable 可避免繼承限制:
public class Test implements Runnable {
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("hello_" + i);
}
}
}
// 啟動方式
Runnable tt = new Test();
Thread th = new Thread(tt);
th.start();
isAlive():判斷線程是否處於活躍狀態(已啟動未終止)。join():等待該線程終止;join(long timeout) 可設超時。sleep(long ms) / sleep(long ms, int ns):靜態方法,讓當前線程休眠指定時間。stop():不推薦使用,會導致鎖釋放不當、數據不一致。import java.awt.*;
public class TimerThread extends Thread {
Component comp; // 需重繪的組件
int timeDiff; // 重繪間隔
volatile boolean shouldRun = true; // volatile 保證可見性
public TimerThread(Component comp, int timeDiff) {
this.comp = comp;
this.timeDiff = timeDiff;
}
public void run() {
while (shouldRun) {
try {
comp.repaint();
sleep(timeDiff);
} catch (Exception e) {}
}
}
}
volatile 確保多線程間對 shouldRun 修改的可見性,是線程安全終止的簡單模式。