基礎概念
1、CPU核心數和線程數的關係
核心數:線程數 = 1:1 ;超線程技術 -> 1:2
2、CPU時間片輪轉機制
RR調度,上下文切換
3、線程和進程
進程:程序運行資源分配的最小單位,進程內部有多個線程,會共享這個進程的資源
線程:CPU調度的最小單位
4、併發和並行
並行:同一時刻,可以處理事情的能力
併發:與時間單位相關,在時間單位內可以處理事情的能力
5、線程的實現
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ThreadDemo {
private static class UserThread extends Thread {
@Override
public void run() {
System.out.println("UserThread");
super.run();
}
}
private static class UserRunnable implements Runnable {
@Override
public void run() {
System.out.println("UserRunnable");
}
}
private static class UserCallable implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("UserCallable");
return "call";
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
UserThread userThread = new UserThread();
userThread.start();
UserRunnable userRunnable = new UserRunnable();
new Thread(userRunnable).start();
UserCallable userCallable = new UserCallable();
FutureTask<String> futureTask = new FutureTask<>(userCallable);
new Thread(futureTask).start();
String call = futureTask.get();
System.out.println("userCallable結果:" + call);
}
}
-------------------------------------------------------------------------------
UserThread
UserRunnable
UserCallable
userCallable結果:call
6、線程的暫停
不推薦使用:
stop()方法:無法保證線程資源釋放,不建議使用
resume()方法:用於繼續執行已經掛起的線程
suspend()方法:掛起,線程不會釋放資源,進入睡眠的狀態。容易引起死鎖問題
推薦使用:
interrupt()方法:中斷一個線程,並不是強迫關閉這個線程。而是由線程本身來決定是否停止。
isInterrupt()方法:判斷當前線程是否處於中斷狀態
static的isInterrupt()方法:判斷當前線程是否處於中斷狀態,中斷標誌位改爲false