- package com.eshore.sweetop.os;
- public class Peterson {
- boolean[] interested=new boolean[2];
- int turn;
- /**
- * @param process
- */
- public void enter(int process){
- int other;
- other=1-process;
- interested[process]=true;
- turn=process;
- while(turn==process && interested[other]==true);
- System.out.println(process+" enter !");
- }
- public void leave(int process){
- interested[process]=false;
- System.out.println(process+" leave !");
- }
- public static void main(String[] args) {
- Thread t1=new MThread(0);
- Thread t2=new MThread(1);
- t1.start();
- t2.start();
- }
- static Peterson p=new Peterson();
- static class MThread extends Thread{
- public MThread(int process){
- this.process=process;
- }
- int process;
- @Override
- public void run(){
- p.enter(process);
- System.out.println("work "+process);
- for (int i = 0; i < 100; i++) {
- try {
- this.sleep(12);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println(process+":"+i);
- }
- p.leave(process);
- }
- }
- }
Peterson算法实现线程互斥
最新推荐文章于 2022-11-03 10:13:07 发布