一
獨占:通過阻止多個並發行為間的有害干擾來維護狀態的一致性
狀態依賴:觸發
成功的狀態決定的
客戶Client: Client Object 期待某個動作的執行
服務Serverce :包括執行這個動作的代碼
主體
Synchronized: 防止並法導致數據不一致
使用synchronized關鍵字來定義方法就會鎖定類中所有使用synchronzied關鍵字定義的靜態方法或非靜態方法
不同的對象實例的synchronized方法是不相干擾的
對於修飾靜態的方法它可以對類的所有對象實例起作用
在非靜態代碼塊中多數是用this
規則
二
(
ExecutorService exec = Executors
for(int =
exec
exec
}
(
ExecutorService exec = Executors
for(int =
exec
exec
}
(
SingleThreadPool 就好象是線程數量為
ExecutorService exec = Executors
for(int =
exec
exec
}
Runnable是執行工作的獨立任務
package
/**
* @ Class CallableDemo
* @ Description
* @ Company OpenData
* @ Author yinlei
* @ Version
* @ Date Mar
*/
import java
import ncurrent
import ncurrent
import ncurrent
import ncurrent
public class CallableDemo{
public static void main(String[] args){
ExecutorService exec = Executors
ArrayList<Future<String>> results = new ArrayList<Future<String>>();
for(int i =
results
}
for(Future<String> fs:results){
try{
if(fs
System
}
} catch(Exception ex){
ex
} finally{
exec
}
}
}
}
class TaskWithResult implements Callable<String>{
private int id;
public TaskWithResult(int id){
this
}
public String call(){
return
}
}
//結果
result of TaskWithResult
result of TaskWithResult
result of TaskWithResult
result of TaskWithResult
result of TaskWithResult
result of TaskWithResult
result of TaskWithResult
result of TaskWithResult
result of TaskWithResult
result of TaskWithResult
sleep() 和wait()方法的區別
sleep是Thread類的靜態方法
wait是Object的方法
sleep()是讓某個線程暫停運行一段時間
而wait()
而在
本質的區別是一個線程的運行狀態控制
package
/**
* @ Class Joining
* @ Description
* @ Company OpenData
* @ Author yinlei
* @ Version
* @ Date Mar
*/
class Sleeper extends Thread{
private int duration;
public Sleeper(String name
super(name);
duration = sleepTime;
start();
}
public void run(){
try{
sleep(duration);
}catch(InterruptedException ex){
System
}
System
}
}
class Joiner extends Thread{
private Sleeper sleeper;
public Joiner(String name
super(name);
this
start();
}
public void run(){
try{
sleeper
} catch(InterruptedException ex){
System
}
System
}
}
public class Joining {
public static void main(String []args){
Sleeper sleepy = new Sleeper(
Sleeper grumpy = new Sleeper(
Joiner dopey = new Joiner(
Joiner doc = new Joiner(
grumpy
}
}
out put:
Grumpy was interrupted
Grumpy has awakened
Doc join completed
Sleepy has awakened
Dopey join completed
public synchronized int next(){
try{
return
}catch(){
}
}
private Lock lock = new ReentrantLock();
public int next(){
try{
lock
return
} catch(){
lock
}
使用synchronized關鍵字和顯示Lock都可以解決資源同步的問題
能嘗試獲取鎖一段時間
它的功用非常簡單
通常通過get()
package
import java
import ncurrent
import ncurrent
import ncurrent
class Accessor implements Runnable{
private final int id;
public Accessor(int idn){id = idn;}
public void run(){
while(!Thread
ThreadLocalVariableHolder
System
Thread
}
}
public String toString(){
return
}
}
public class ThreadLocalVariableHolder{
private static ThreadLocal<Integer> value=
new ThreadLocal<Integer>(){
private Random rand = new Random(
protected synchronized Integer initialValue(){
return rand
}
};
public static void increment(){
value
}
public static int get(){return value
public static void main(String []args) throws Exception{
ExecutorService exec = Executors
for(int i =
exec
}
TimeUnit
exec
}
}
//output:
#
#
#
#
#
#
#
#
#
任務的run()方法通常總會有某種形式的循環
通常
由於線程的本質特性
package
public class ThreadException implements Runnable {
public void run() {
throw new RuntimeException(
}
public static void main(String []args){
try{
Thread t = new Thread(new ThreadException());
t
} catch(Exception ex){
System
ex
}
}
}
/* output
Exception in thread
at
at java
也就是說tyr catch 無法捕獲到從run 方法裡逃逸的異常
Thread
它允許你在每個Thread對象上都附著一個異常處理器
package
public class ThreadException implements Runnable {
public void run() {
throw new RuntimeException(
}
public static void main(String[] args) {
Thread t = new Thread(new ThreadException());
t
t
}
}
//異常處理器
class MyUncaughtException implements Thread
public void uncaughtException(Thread t
System
}
}
/* output
Thread[Thread
多個任務
那麼如何使得多個任務可以在一起彼此協作
eg:一個是將蠟塗到Car上
car 對象通過wait
package
import ncurrent
import ncurrent
import ncurrent
class Car{
private boolean waxOn = true;//默認為拋光狀態
//打蠟完成
public synchronized void waxed(){
waxOn = false;
notifyAll();
}
//拋光完成
public synchronized void buffing(){
waxOn = true;
notifyAll();
}
//是否拋光結束
public synchronized void waitForWaxed() throws InterruptedException{
while(!waxOn){
wait();
}
}
//是否打蠟結束
public synchronized void waitForBuffing() throws InterruptedException{
while(waxOn){
wait();
}
}
}
//打蠟
class WaxOn implements Runnable{
private Car car;
public WaxOn(Car car){
this
}
public void run() {
try{
while(!Thread
car
System
TimeUnit
car
}
} catch (Exception ex){
ex
}
}
}
//拋光
class Buffing implements Runnable{
private Car car;
public Buffing(Car car){
this
}
public void run() {
try{
while(!Thread
car
System
TimeUnit
car
}
} catch (Exception ex){
ex
}
}
}
public class WaxOMatic {
public static void main(String []args) {
try{
Car car = new Car();
ExecutorService exec = Executors
exec
exec
TimeUnit
exec
} catch (InterruptedException ex){
ex
}
}
}
/* output
Wax On!
Buffing On!
Wax On!
Buffing On!
Wax On!
Buffing On!
打蠟和拋光相繼進行
典型的哲學家就餐就是死鎖問題
(
(
(
(
通過破除死鎖四個必要條件之一
哲學家就餐問題:該問題涉及到五個哲學家
他們分別坐在位於一個圓形餐桌周圍的五把椅子上
分別擺放在每兩個相鄰座位的中間
當哲學家思考時
但他很可能僅拿到一根
只有他同時拿到兩根筷子時他才能開始進餐
他將兩根筷子分別放回原位
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27658.html