在不使用内置互斥功能的情况下用Java实现Petersons解决方案

问题描述

因此,对于我大学里的一个问题,我们被要求为该Java程序实现Petersons解决方案,并且已经声明我们只能添加一些变量,而不能显着更改代码。我对此很陌生,并努力使自己步入正轨,并希望获得任何帮助。

public class SlowRaceTwo {

      public static void main(String args []) throws Exception {

          MyThread.count = 0 ;

          MyThread thread1 = new MyThread() ;
          thread1.name = "A" ;
      

          MyThread thread2 = new MyThread() ;
          thread2.name = "B" ;
         
          thread1.start() ;
          thread2.start() ;

          thread2.join() ;
          thread1.join() ;

          System.out.println("MyThread.count = " + MyThread.count) ;
      }
  }

  class MyThread extends Thread {

      volatile static int count ;
      String name ;
      
      


      public void run() {

          for(int i = 0 ; i < 10 ; i++) {
              
  /* Critical section */
            delay() ;
            int x = count ;
            System.out.println("Thread " + name + " read " + x);
            delay() ;
            count = x + 1 ;
            System.out.println("Thread " + name + " wrote " + (x + 1)) ;
             /* */
  
          }
      }

      void delay() {

          int delay = (int) (1000 * Math.random()) ;
          try {
              Thread.sleep(delay) ;
          }
          catch(Exception e) {
          }
      }
  }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...