多執行緒高併發筆記二

2021-09-29 10:04:31 字數 1730 閱讀 8578

併發主要有三塊知識點:

synchronized / 同步容器 / threadpool,executor

lock/reentrantlock

lock lock = new reentrantlock();

//公平鎖 lock lock = new reentrantlock(true);

void m1()

boolean f =lock.trylock(); //嘗試鎖定

try catch (interruptedexception e)

可以被打斷的鎖:t1 鎖一直不放,t2不打算讓他等了,打斷t2

public class mythreadfour 

} catch (interruptedexception e) finally

}void m1() catch (interruptedexception e)

}public static void main(string args) catch (interruptedexception e)

thread1.start();

system.out.println("準備打斷");

try catch (interruptedexception e)

thread1.interrupt();

}}

reentrantlock 和 synchronized區別:

reentrantlock:

1  可以設定公平鎖/非公平鎖

2  能實現synchronized的功能

3  可以進行嘗試鎖定,如果鎖定怎麼樣,如果沒鎖定如何

4  可以被打斷

synchronized:非公平鎖

condition版本

public class mythreadfive  catch (interruptedexception e) 

this.notifyall(); //多執行緒中建議使用notifyall 而不是notify

}return list.remove(num);

}synchronized void put(object obj) catch (interruptedexception e)

this.notifyall();

}list.add(obj);

}synchronized int getcount()

public static void main(string args)

}/**

* 使用lock版本

*/class mythreadfive1 catch (interruptedexception e)

}object obj =list.remove(num);

prod.signalall();

return obj;

}void put(object obj) catch (interruptedexception e)

sumer.signalall();

}list.add(obj);

}int getcount()

}

threadlocal:執行緒區域性變數 

threadlocalp = null;
自己的執行緒自己用,若a執行緒放入乙個物件,則b執行緒獲得不到這個物件

多執行緒高併發

修飾靜態方法鎖的是class,非靜態鎖方法鎖的是this,只有拿到這個物件才可以繼續執行 synchronized是可重入鎖 執行緒1的方法1呼叫執行緒2的方法2,判斷是同一把鎖,在同乙個執行緒,可以呼叫。synchronized的鎖公升級 hotsport 鎖公升級過程 保證執行緒可見性 mesi...

多執行緒高併發

個人總結,帶有個人主觀,請選擇性 1,實現 runable 2,使用 thread 3,執行緒池建立 executorse newcachedthreadpool 其實哪有那麼多建立方式,本質上都是實現了runable 介面。只列出大部分使用的方法,並未代表所有執行緒方法,後續會新增實際的例子,以供...

多執行緒與高併發系列(二)

2.threadpoolexecutor 3.執行緒池種類 public class mythread extends thread mythread t1 newmythread t1.start public class mythread extends otherclass implement...