main 線程(主線程)+ GC 線程 + 其他守護線程public class MyThread extends Thread {
@Override public void run() {
for (int i = 0; i < 60; i++)
System.out.println(getName() + " run " + i);
}
}
public class Demo {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start(); // 啟動線程,調用 run()
// t.run(); // 直接調用,不啟動新線程!
for (int i = 0; i < 60; i++)
System.out.println("main " + i);
}
}
public class Ticket implements Runnable {
private static int tick = 100;
private final Object lock = new Object();
public void run() {
while (true) {
synchronized (lock) { // 同步代碼塊
if (tick > 0)
System.out.println(Thread.currentThread().getName() + ":" + tick--);
else
return;
}
}
}
}
public class Demo {
public static void main(String[] args) {
Ticket task = new Ticket();
new Thread(task, "窗口A").start();
new Thread(task, "窗口B").start();
new Thread(task, "窗口C").start();
}
}
| 維度 | 繼承 Thread | 實現 Runnable |
|---|---|---|
| 繼承限制 | 單繼承 | 無限制 |
| 代碼復用 | 差 | 好(同任務多線程) |
| 線程對象 | this | new Thread(runnable) |
| 推薦度 | 低 | 高 |
start():啟動線程(異步)run():普通方法調用(同步)Thread.currentThread():獲取當前線程對象getName()/setName():獲取/設置線程名sleep(ms):靜態方法,當前線程休眠,不釋放鎖join():等待該線程終止NEW → RUNNABLE → BLOCKED/WAITING/TIMED_WAITING → TERMINATED
sleep()/wait() → 進入阻塞/等待notify()/notifyAll() → 喚醒多線程操作共享數據,非原子操作被打斷 → 數據不一致。
synchronized(lockObject) {
// 臨界區:操作共享數據
}
public synchronized void add(int n) { ... } // 鎖 this
public static synchronized void staticAdd() { ... } // 鎖 Class 對象
Lock lock = new ReentrantLock();
lock.lock();
try { ... } finally { lock.unlock(); }
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() { return INSTANCE; }
}
public class Singleton {
private static volatile Singleton instance; // volatile 禁止指令重排
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
public class DeadLockDemo {
static Object lockA = new Object();
static Object lockB = new Object();
public static void main(String[] args) {
new Thread(() -> {
synchronized (lockA) {
sleep(10);
synchronized (lockB) { System.out.println("A->B"); }
}
}).start();
new Thread(() -> {
synchronized (lockB) {
sleep(10);
synchronized (lockA) { System.out.println("B->A"); }
}
}).start();
}
}
System.identityHashCode 排序)tryLock(timeout) 避免無限等待掌握 Runnable + Thread 創建、synchronized/Lock 同步、volatile 可見性、DCL 單例、死鎖預防,是 Java 併發編程的必修課。實戰中優先使用 java.util.concurrent 高級工具(線程池、並發集合、同步器)。