多線程一定快嗎纲菌?
答案是不一定钱慢。當(dāng)并發(fā)執(zhí)行的累積數(shù)量一定以內(nèi),并行會比串行執(zhí)行要慢缘眶,此處用的測試用例是累加嘱根,那么為什么會出現(xiàn)這種情況呢?
這是因為線程的創(chuàng)建的上下文切換的開銷
上下文切換
單核處理器也支持多線程執(zhí)行代碼巷懈,CPU通過給每個線程分配CPU時間片來實現(xiàn)這個機制该抒,因為時間片非常短,所以CPU通過不停切換線程執(zhí)行的顶燕,時間一般是即使毫秒(ms)
public class ConcurrencyTest {
private static final long count = 100001;
public static void main(String[] args) throws InterruptedException{
concurrency();
serial();
}
private static void concurrency() throws InterruptedException {
long start = System.currentTimeMillis();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
int a = 0;
for(long i = 0;i<count;i++) {
a += 5;
}
}
});
thread.start();
int b = 0;
for(long i = 0;i<count;i++) {
b--;
}
long time = System.currentTimeMillis()-start;
thread.join();
System.out.println("concurrency:"+time+"ms,"+" b="+b);
}
private static void serial() {
long start = System.currentTimeMillis();
int a = 0;
for(long i =0;i<count;i++) {
a +=5;
}
int b = 0;
for(long i =0;i<count;i++) {
b--;
}
long time = System.currentTimeMillis() - start;
System.out.println("serial:"+time+"ms,"+" b="+b);
}
}
這就像我們同時讀兩本書凑保,當(dāng)我們在讀一本英文的技術(shù)書時,發(fā)現(xiàn)某個單詞不認識涌攻,于是便打開中英文字典欧引,但是在放下英文技術(shù)書之前,大腦必須先記住這本書讀到了多少頁的第多少行恳谎,等查完單詞之后芝此,能夠繼續(xù)讀這本書。這樣的切換是會影響讀書效率的因痛,同樣上下文切換也會影響多線程的執(zhí)行速度
如何減少上下文切換呢婚苹?
無鎖并發(fā)編程 使用一下辦法來避免使用鎖
CAS算法 Compare And Swap 即比較和替換
使用最小線程數(shù)
死鎖列子
package com.hunau;
public class DeadLockDemo {
private static String A = "A";
private static String B = "B";
public static void main(String[] args) {
new DeadLockDemo().deadLock();
}
private void deadLock() {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized(A) {
try {
Thread.currentThread().sleep(2000);
}catch(InterruptedException e) {
e.printStackTrace();
}
synchronized(B) {
System.out.println("1");
}
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized(B) {
synchronized(A) {
System.out.println("2");
}
}
}
}) ;
t1.start();
t2.start();
}
}