JUC全程:java.util.concurrent,指在併發編程中使用的工具類
一、進程和線程區別
**進程:**進程是一個具有一定獨立功能的程序關於某個數據集合的一次運行活動。它是操作系統動態執行的基本單元,在傳統的操作系統中,進程既是基本的分配單元,也是基本的執行單元。
**線程:**通常在一個進程中可以包含若干個線程,當然一個進程中至少有一個線程,不然沒有存在的意義。線程可以利用進程所擁有的資源,在引入線程的操作系統中,通常都是把進程作爲分配資源的基本單位,而把線程作爲獨立運行和獨立調度的基本單位,由於線程比進程更小,基本上不擁有系統資源,故對它的調度所付出的開銷就會小得多,能更高效的提高系統多個程序間併發執行的程度。
二、進程和線程的例子
使用QQ,查看進程一定有一個QQ.exe的進程,我可以用qq和A文字聊天,和B視頻聊天,給C傳文件,給D發一段語言,QQ支持錄入信息的搜索。
大學的時候寫論文,用word寫論文,同時用QQ音樂放音樂,同時用QQ聊天,多個進程。
word如沒有保存,停電關機,再通電後打開word可以恢復之前未保存的文檔,word也會檢查你的拼寫,兩個線程:容災備份,語法檢查
三、線程狀態
Thread.State
public enum State {
/**
* Thread state for a thread which has not yet started.
*/
NEW,(新建)
/**
* Thread state for a runnable thread. A thread in the runnable
* state is executing in the Java virtual machine but it may
* be waiting for other resources from the operating system
* such as processor.
*/
RUNNABLE,(準備就緒)
/**
* Thread state for a thread blocked waiting for a monitor lock.
* A thread in the blocked state is waiting for a monitor lock
* to enter a synchronized block/method or
* reenter a synchronized block/method after calling
* {@link Object#wait() Object.wait}.
*/
BLOCKED,(阻塞)
/**
* Thread state for a waiting thread.
* A thread is in the waiting state due to calling one of the
* following methods:
* <ul>
* <li>{@link Object#wait() Object.wait} with no timeout</li>
* <li>{@link #join() Thread.join} with no timeout</li>
* <li>{@link LockSupport#park() LockSupport.park}</li>
* </ul>
*
* <p>A thread in the waiting state is waiting for another thread to
* perform a particular action.
*
* For example, a thread that has called <tt>Object.wait()</tt>
* on an object is waiting for another thread to call
* <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
* that object. A thread that has called <tt>Thread.join()</tt>
* is waiting for a specified thread to terminate.
*/
WAITING,(不見不散)
/**
* Thread state for a waiting thread with a specified waiting time.
* A thread is in the timed waiting state due to calling one of
* the following methods with a specified positive waiting time:
* <ul>
* <li>{@link #sleep Thread.sleep}</li>
* <li>{@link Object#wait(long) Object.wait} with timeout</li>
* <li>{@link #join(long) Thread.join} with timeout</li>
* <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
* <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
* </ul>
*/
TIMED_WAITING,(過時不候)
/**
* Thread state for a terminated thread.
* The thread has completed execution.
*/
TERMINATED;(終結)
}
四、wait/sleep的區別
wait放開手去睡,放開手裏的鎖
sleep握緊手去睡,醒了手裏還有鎖
五、什麼是併發,什麼是並行
併發:同一時刻多個線程在訪問同一個資源,多個線程對一個點
例子:小米9今天上午10點,限量搶購
春運搶票
電商秒殺…
並行:多項工作一起執行,之後再彙總
例子:泡方便麪,電水壺燒水,一邊撕調料倒入桶中