Peterson算法实现线程互斥

  1. package com.eshore.sweetop.os;
  2. public class Peterson {
  3.     boolean[] interested=new boolean[2];
  4.     int turn;
  5.     
  6.     /**
  7.      * @param process
  8.      */
  9.     public void enter(int process){
  10.         int other;  
  11.         other=1-process;
  12.         interested[process]=true;
  13.         turn=process;
  14.         while(turn==process && interested[other]==true);
  15.         System.out.println(process+" enter !");
  16.     }
  17.     
  18.     public void leave(int process){
  19.         interested[process]=false;
  20.         System.out.println(process+" leave !");
  21.     }
  22.     
  23.     public static void main(String[] args) {
  24.         Thread t1=new MThread(0);
  25.         Thread t2=new MThread(1);
  26.         t1.start();
  27.         t2.start();
  28.     }
  29.     
  30.     static Peterson p=new Peterson();       
  31.     static class MThread extends Thread{
  32.         
  33.         public MThread(int process){
  34.             this.process=process;
  35.         }
  36.         
  37.         int process;
  38.         @Override
  39.         public void run(){
  40.             p.enter(process);
  41.             System.out.println("work "+process);
  42.             for (int i = 0; i < 100; i++) {
  43.                 try {
  44.                     this.sleep(12);
  45.                 } catch (InterruptedException e) {
  46.                     // TODO Auto-generated catch block
  47.                     e.printStackTrace();
  48.                 }
  49.                 System.out.println(process+":"+i);
  50.             }
  51.             p.leave(process);
  52.         }
  53.     }
  54. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值