?? criticalsection.java
字號(hào):
//用某一塊的同步代替對(duì)整個(gè)方法的同步.
//用個(gè)安全線程保護(hù)一個(gè)類不安全線程.
import java.util.*;
class Pair { // 線程不安全的.
private int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public Pair() { this(0, 0); }
public int getX() { return x; }
public int getY() { return y; }
public void incrementX() { x++; }
public void incrementY() { y++; }
public String toString() {
return "x: " + x + ", y: " + y;
}
class PairValuesNotEqualException
extends RuntimeException {
public PairValuesNotEqualException() {
super("這一對(duì)值不相等: " + Pair.this);
}
}
// 兩個(gè)變量必須相等.
public void checkState() {
if(x != y)
throw new PairValuesNotEqualException();
}
}
//保護(hù)內(nèi)部線程的安全
abstract class PairManager {
protected Pair p = new Pair();
private List storage = new ArrayList();
public synchronized Pair getPair() {
// 做一個(gè)備份來保護(hù)原線程的安全.
return new Pair(p.getX(), p.getY());
}
protected void store() { storage.add(getPair()); }
// 一個(gè)模板方法.
public abstract void doTask();
}
//同步整個(gè)方法.
class PairManager1 extends PairManager {
public synchronized void doTask() {
p.incrementX();
p.incrementY();
store();
}
}
//用臨界區(qū)
class PairManager2 extends PairManager {
public void doTask() {
synchronized(this) {
p.incrementX();
p.incrementY();
}
store();
}
}
class PairManipulator extends Thread {
private PairManager pm;
private int checkCounter = 0;
private class PairChecker extends Thread {
PairChecker() { start(); }
public void run() {
while(true) {
checkCounter++;
pm.getPair().checkState();
}
}
}
public PairManipulator(PairManager pm) {
this.pm = pm;
start();
new PairChecker();
}
public void run() {
while(true) {
pm.doTask();
}
}
public String toString() {
return "一對(duì)數(shù): " + pm.getPair() +
" 檢查 = " + checkCounter;
}
}
public class CriticalSection {
public static void main(String[] args) {
//測(cè)試兩種不同的方法.
final PairManipulator
pm1 = new PairManipulator(new PairManager1()),
pm2 = new PairManipulator(new PairManager2());
new Timer(true).schedule(new TimerTask() {
public void run() {
System.out.println("pm1: " + pm1);
System.out.println("pm2: " + pm2);
System.exit(0);
}
}, 500); // 500毫秒后開始運(yùn)行.
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -