volatile
如下代碼
static byte value=0;
static boolean finish=false;
public static void testVolatile() throws InterruptedException {
value=0;
finish=false;
new Thread(new Runnable() {
@Override
public void run() {
while(value==0&&!finish);
console.info("value is "+value+" finish is "+finish);
}
}).start();
Thread.sleep(1000);
new Thread(new Runnable() {
@Override
public void run() {
value=10;
finish=true;
console.info("has set the finish");
}
}).start();
}
第一個(gè)線程的死循環(huán) 并不會(huì)因?yàn)榈诙€(gè)線程的設(shè)置變量結(jié)束,這是因?yàn)閏pu緩存的問題
volatile static byte value=0;
如果將value的改為volatile變量那么第一個(gè)線程就會(huì)如期結(jié)束扣墩。因?yàn)槊看巫x取value并不去使用緩存
concurrent的BlockingQueue
BlockingQueue是一個(gè)線程安全的隊(duì)列接口 竹椒,提供了 put take poll等方法
實(shí)現(xiàn)類有 ArrayBlockingQueue LinkedBlockingQueue PriorityBlockingQueue
public static class Message implements Comparable<Message>{
public int value=0;
public Message(int value) {
this.value = value;
}
@Override
public int compareTo(Message o) {
return value-o.value;
}
}
public static void blockingQueueTest(){
PriorityBlockingQueue <Message> blockingDeque=new PriorityBlockingQueue <Message>();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<100;i++) {
try {
console.info(blockingDeque.take().value);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
},"消費(fèi)者").start();
new Thread(new Runnable() {
@Override
public void run() {
blockingDeque.put(new Message(100));
blockingDeque.put(new Message(0));
blockingDeque.put(new Message(0));
blockingDeque.put(new Message(100));
}
},"生產(chǎn)者").start();
}
看到消費(fèi)者拿到的消息是排序過(guò)的
concurren包的線程池
Executors.newScheduledThreadPool 創(chuàng)建固定大小的線程池
Executors.newFixedThreadPool 創(chuàng)建固定大小的線程池
Executors.newCachedThreadPool 創(chuàng)建緩存線程池 從0 開始 每個(gè)線程存貨一分鐘
Executors.newSingleThreadExecutor 創(chuàng)建只有一個(gè)線程的線程池
實(shí)際上都是創(chuàng)建了一個(gè)ThreadPoolExecutor 控制了不同參數(shù)
/**
*
* corePoolSize 線程池最小保持線程數(shù) 即是他們處于空閑狀態(tài)
* maximumPoolSize 線程池最大線程數(shù)
* keepAliveTime 如果線程數(shù)超出最小保持 那么線程最大空閑存活實(shí)際
* unit 存活時(shí)間單位單位
* 初始工作的緩沖區(qū)
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
}
ReentrantReadWriteLock
讀寫鎖 把讀和寫分別變成鎖 比synchronized更輕量控制更方便
讀鎖排斥寫鎖 不排斥讀鎖
寫鎖排斥其他鎖
public static void ReadWriteLock(){
ReadWriteLock reentrantLock=new ReentrantReadWriteLock();
Lock readLock=reentrantLock.readLock();
Lock writeLock=reentrantLock.writeLock();
for(int i=0;i<2;i++)
new Thread(new Runnable() {
@Override
public void run() {
readLock.lock();
console.info("獲取到了讀鎖");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
writeLock.lock();
console.info("獲取到了寫鎖");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}