併發程式設計雜篇

2021-07-25 23:30:29 字數 3066 閱讀 7472

/**

* atomically adds the given value to the current value.

**@param delta the value to add

*@return the updated value

*/public

final

intaddandget(int delta)

}

public

class dubblesingleton catch (interruptedexception e)

synchronized (dubblesingleton.class) }}

return ds;

}public

static

void

main(string args)

},"t1");

thread t2 = new thread(new runnable()

},"t2");

thread t3 = new thread(new runnable()

},"t3");

t1.start();

t2.start();

t3.start();

}}

這裡面最有疑問的應該是第二次檢查了,原因是因為但執行緒1在鎖定進入例項化的時候,執行緒2和執行緒3也通過了第一次檢查,當執行緒1例項化後執行緒2和執行緒3還會進入同步塊進行例項化物件,因此需要在同步**塊中進行判斷是否有例項化物件,防止再次例項化物件,如果還是不清楚把上面**進行debug一步步執行就知道了。

public

class singletion

public

static singletion getinstance()

}

public

class usefuture implements callable

/*** 這裡是真實的業務邏輯,其執行可能很慢

*/@override

public string call() throws exception

//主控制函式

public

static

void

main(string args) throws exception catch (exception e)

//呼叫獲取資料方法,如果call()方法沒有執行完成,則依然會進行等待

system.out.println("資料:" + future.get());

system.out.println("資料:" + future2.get());

executor.shutdown();

}}

public

class usecyclicbarrier

@override

public

void

run() catch (interruptedexception e) catch (brokenbarrierexception e)

system.out.println(name + " go!!");

} }

public

static

void

main(string args) throws ioexception, interruptedexception

}

從上面的**可以看出,當執行緒池executors啟動的執行緒達到cyclicbarrier初始化時給的數字,那所有的執行緒都將立即執行,不然程式會一直阻塞在那裡。

public

class usesemaphore catch (interruptedexception e)

} };

exec.execute(run);

} try catch (interruptedexception e)

// 退出執行緒池

exec.shutdown();

} }

public

class usereentrantlock catch (interruptedexception e) finally

}public

void

method2() catch (interruptedexception e) finally

}public

static

void

main(string args)

}, "t1");

t1.start();

try catch (interruptedexception e)

}}

public

class usereentrantreadwritelock catch (exception e) finally

}public

void

write() catch (exception e) finally

}public

static

void

main(string args)

}, "t1");

thread t2 = new thread(new runnable()

}, "t2");

thread t3 = new thread(new runnable()

}, "t3");

thread t4 = new thread(new runnable()

}, "t4");

// t1.start();

// t2.start();

// t1.start(); // r

// t3.start(); // w

t3.start();

t4.start();

}}

併發程式設計 基礎篇

當前物件型別 物件頭長度 陣列3字長 非陣列2字長 長度內容 說明1個字長 32bit 64bit mark world 儲存物件的hashcode以及鎖的資訊 1個字長 class metedata address 儲存物件型別資料的指標 1個字長 array length 陣列長度 如果物件是陣...

併發程式設計 執行緒篇

public class shutdown private static class runner implements runnable system.out.println count i i public void cancel 本質 對乙個物件的監視器 monitor 進行獲取,而這個獲取過...

Java併發程式設計(二)之併發程式設計挑戰篇

在進行併發程式設計開發時,會面臨一些挑戰,主要包括三個方面 上下文切換 死鎖 資源限制 挑戰一 上下文切換的挑戰 上下文切換 單個cpu同乙個時刻只能執行一條執行緒,作業系統會給每條執行緒分配時間片來對執行緒進行排程操作,執行緒在得到的時間片內占用cpu資源處理自身資料,當作業系統從乙個執行緒切換到...