進(jìn)程和線程
操作系統(tǒng)中運(yùn)?多個(gè)軟件
1.?個(gè)運(yùn)?中的軟件可能包含多個(gè)進(jìn)程
2.?個(gè)運(yùn)?中的進(jìn)程可能包含多個(gè)線程CPU 線程和操作系統(tǒng)線程
CPU 線程
多核 CPU 的每個(gè)核各?獨(dú)?運(yùn)?,因此每個(gè)核?個(gè)線程
「四核?線程」:CPU 硬件?在硬件級(jí)別對(duì) CPU 進(jìn)?了?核多線程的?持(本質(zhì)上依然是每個(gè)核?個(gè)線程)操作系統(tǒng)線程:操作系統(tǒng)利?時(shí)間分?的?式,把 CPU 的運(yùn)?拆分給多條運(yùn)?邏輯,即為操作系統(tǒng)的線程單核 CPU 也可以運(yùn)?多線程操作系統(tǒng)
線程是什么:按代碼順序執(zhí)?下來(lái),執(zhí)?完畢就結(jié)束的?條線
UI 線程為什么不會(huì)結(jié)束?因?yàn)樗诔跏蓟戤吅髸?huì)執(zhí)?死循環(huán),循環(huán)的內(nèi)容是刷新界?
多線程的使?
-
Thread
Thread thread = new Thread() {
@Override
public void run() {
System.out.println("Thread started!");
}
};
thread.start();
-
Runnable
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Thread with Runnable started!");
}
};
Thread thread = new Thread(runnable);
thread.start();
-
ThreadFactory
ThreadFactory factory = new ThreadFactory() {
int count = 0;
@Override
public Thread newThread(Runnable r) {
count ++;
return new Thread(r, "Thread-" + count);
}
};
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "
started!");
}
};
Thread thread = factory.newThread(runnable);
thread.start();
Thread thread1 = factory.newThread(runnable);
thread1.start();
Executor 和線程池
- newCachedThreadPool()
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Thread with Runnable started!");
}
};
Executor executor = Executors.newCachedThreadPool();
executor.execute(runnable);
executor.execute(runnable);
executor.execute(runnable);
- 短時(shí)批量處理: newFixedThreadPool()
ExecutorService executor = Executors.newFixedThreadPool(20);
for (Bitmap bitmap : bitmaps) {
executor.execute(bitmapProcessor(bitmap));
}
executor.shutdown();
- Callable 和 Future
Callable<String> callable = new Callable<String>() {
@Override
public String call() {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Done!";
}
};
ExecutorService executor = Executors.newCachedThreadPool();
Future<String> future = executor.submit(callable);
try {
String result = future.get();
System.out.println("result: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
線程同步與線程安全
synchronized
- synchronized ?法
private synchronized void count(int newValue) {
x = newValue; y = newValue;
if (x != y) {
System.out.println("x: " + x + ", y:" + y);
}
}
- synchronized 代碼塊
private void count(int newValue) {
synchronized (this) {
x = newValue; y = newValue;
if (x != y) {
System.out.println("x: " + x + ", y:" + y);
}
}
}
synchronized (monitor1) {
synchronized (monitor2) {
name = x + "-" + y;
}
}
-
synchronized 的本質(zhì)
保證?法內(nèi)部或代碼塊內(nèi)部資源(數(shù)據(jù))的互斥訪問(wèn)。即同?時(shí)間、由同?個(gè)
Monitor 監(jiān)視的代碼,最多只能有?個(gè)線程在訪問(wèn)
image.png
保證線程之間對(duì)監(jiān)視資源的數(shù)據(jù)同步。即,任何線程在獲取到 Monitor 后的第?時(shí)
間,會(huì)先將共享內(nèi)存中的數(shù)據(jù)復(fù)制到??的緩存中;任何線程在釋放 Monitor 的第?
時(shí)間,會(huì)先將緩存中的數(shù)據(jù)復(fù)制到共享內(nèi)存中。
image.png - volatile
1.保證加了 volatile 關(guān)鍵字的字段的操作具有原?性和同步性,其中原?性相當(dāng)于實(shí)現(xiàn)了針對(duì)
2.單?字段的線程間互斥訪問(wèn)。因此 volatile 可以看做是簡(jiǎn)化版的 synchronized。
volatile 只對(duì)基本類(lèi)型 (byte、char、short、int、long、float、double、boolean) 的賦值
操作和對(duì)象的引?賦值操作有效。 - java.util.concurrent.atomic 包
下?有 AtomicInteger AtomicBoolean 等類(lèi),作?和 volatile 基本?致,可以看做是通?版的 volatile。 - Lock / ReentrantReadWriteLock
同樣是「加鎖」機(jī)制。但使??式更靈活,同時(shí)也更麻煩?些。
Lock lock = new ReentrantLock();
...
lock.lock();
try {
x++;
} finally {
lock.unlock();
}
finally 的作?:保證在?法提前結(jié)束或出現(xiàn) Exception 的時(shí)候,依然能正常釋放鎖
?般并不會(huì)只是使? Lock ,?是會(huì)使?更復(fù)雜的鎖,例如 ReadWriteLock :
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
Lock readLock = lock.readLock();
Lock writeLock = lock.writeLock();
private int x = 0;
private void count() {
writeLock.lock();
try {
x++;
} finally {
writeLock.unlock();
}
}
private void print(int time) {
readLock.lock();
try {
for (int i = 0; i < time; i++) {
System.out.print(x + " ");
}
System.out.println();
} finally {
readLock.unlock();
}
}
線程安全問(wèn)題的本質(zhì):
在多個(gè)線程訪問(wèn)共同的資源時(shí),在某?個(gè)線程對(duì)資源進(jìn)?寫(xiě)操作的中途(寫(xiě)?已經(jīng)開(kāi)始,但還沒(méi)結(jié)束),其他線程對(duì)這個(gè)寫(xiě)了?半的資源進(jìn)?了讀操作,或者基于這個(gè)寫(xiě)了?半的資源進(jìn)?了寫(xiě)操作,導(dǎo)致出現(xiàn)數(shù)據(jù)錯(cuò)誤。鎖機(jī)制的本質(zhì):
通過(guò)對(duì)共享資源進(jìn)?訪問(wèn)限制,讓同?時(shí)間只有?個(gè)線程可以訪問(wèn)資源,保證了數(shù)據(jù)的準(zhǔn)確性。不論是線程安全問(wèn)題,還是針對(duì)線程安全問(wèn)題所衍?出的鎖機(jī)制,它們的核?都在于共享的資 源,?不是某個(gè)?法或者某??代碼。

