具体操作类
class MyMutexPlus
package myOperationSystem.DEMO2;
public class MyMutexPlus implements Runnable {
private int mutex = 1; //互斥信号量
private int count = 0; //计数器,用来结束线程
//P操作
public synchronized void P() {
mutex--;
if (mutex >= 0) {
return;
} else {
try {
System.out.println("\t\t" + Thread.currentThread().getName() + " 正在等待");
wait(); //用wait方法实现阻塞原语block
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//V操作
public synchronized void V() {
mutex++;
if (mutex > 0) {
return;
} else {
notify(); //用notify实现唤醒原语wakeup
}
}
@Override
public void run() {
while (count < 50) {
P();
System.out.println(Thread.currentThread().getName() + " 正在使用临界区资源");
count++;
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " 使用完临界区资源");
V();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
主类:
class MyMutexPlus
package myOperationSystem.DEMO2;
public class MainPlus {
public static void main(String[] args) {
MyMutexPlus mutex = new MyMutexPlus();
Thread t1 = new Thread(mutex, "线程1");
Thread t2 = new Thread(mutex, "线程2");
t1.start();
t2.start();
}
}