📄 criticalsection.java
字号:
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 increamentX() { x++; } public void increamentY() { y++; } public String toString() { return "x: " + x + " y: " + y; } //自定义异常 class PairValuesNotEqualException extends RuntimeException { public PairValuesNotEqualException() { super("Not Equal " + Pair.this); } } public void checkState() { if (x != y) { //抛出异常 throw /* 新建异常对象*/new PairValuesNotEqualException(); } }}//定义虚基类,用于继承abstract class PairManager { protected Pair p = new Pair(); private List storage = new ArrayList(); //返回一个 Pari 对象 public synchronized Pair getPair() { //store return new Pair(p.getX(), p.getY()); } //存储 用 getPair() 方法得到的这个对象 protected void store() { storage.add(getPair()); } //声明 虚 方法 用于继承 public abstract void doTask();}class PairManager1 extends PairManager { //同步方法块 public synchronized void doTask() { //doTask() 方法的作用是:p 对象 的 x y 增加, 然后,通过store()方法存储 p.increamentX(); p.increamentY(); super.store(); }} class PairManager2 extends PairManager { public void doTask() { //同步代码块 synchronized(this){ //doTask() 方法的作用是:p 对象 的 x y 增加, 然后,通过store()方法存储 p.increamentX(); p.increamentY(); super.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++; //PairValuesNotEqualException 异常的检查 pm.getPair().checkState(); } } } public PairManipulator(PairManager pm) { this.pm = pm; //启动 PairManipulator 线程 start(); //Pair 检查 new PairChecker(); } public void run() { while(true) { //执行 PairManager 对象的 doTask() 方法 pm.doTask(); } } //自定义 输出 消息 public String toString() { return "Pair: " + pm.getPair() + " Check: " + checkCounter; }}//定义 启动类public class CriticalSection { public static void main(String[] args) { final PairManipulator pm1 = new PairManipulator(new PairManager1()), pm2 = new PairManipulator(new PairManager2()); new Timer(true/*isDaemon 定义为 守护线程*/).schedule(new TimerTask(){ public void run() { System.out.println("pm1: " + pm1); System.out.println("pm2: " + pm2); System.exit(0); } }, 500); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -