Results 1 to 2 of 2

Thread: mutex

  1. #1
    thescratchy is offline Member
    Join Date
    Dec 2010
    Posts
    2
    Rep Power
    0

    Default mutex

    Hello

    I have the following problem:

    There are 2 villages separated by only one bridge. Each village has many farmers. The farmers want to go to the other village to sell there products.
    They create a deadlock when a farmer from the first village collide with a farmer from the second village.

    Below is my code, but I think I am not "sending them over the bridge". Can someone help me with this?

    Thank you.

    Java Code:
    class Village{
    
      long village1 = 0;
      long village2 = 0;
      boolean useBridge = false;
    
      public void addVillage1(){
        synchronized(this){
          if(!useBridge){
    	useBridge = true;
    	village1++;
    	useBridge = false;
    
          }
        }
      }
    
      public void addVillage2(){
        synchronized(this){
          if(!useBridge){
    	useBridge = true;
    	village2++;
    	useBridge = false;
          }
        }
      }
    
      public void write(){
          System.out.println("first is: " + village1 + " second is: " + village2);
      }
        
    }
    
    class Farmers{
    
    
      static Village village = new Village(); 
    
    
      public static void main(String [] args){
    
       farmer1Thread f1 = new farmer1Thread();
       farmer1Thread f11 = new farmer1Thread();
       farmer2Thread f2 = new farmer2Thread();
    
       f1.start();
       f11.start();
       f2.start();
       try{
         f1.join();
         f11.join();
         f2.join();
          
        } catch(InterruptedException e){}
    
       village.write();
    
      }
    
    
      public static class farmer1Thread extends Thread{
        public void run(){
          
          for(int i=0; i<1000;i++)
    	village.addVillage2();
          
        }
      }
    
      public static class farmer2Thread extends Thread{
        public void run(){
          for(int i=0; i<1000; i++)
    	village.addVillage1();
          
        }
      }
    }

  2. #2
    toadaly is offline Senior Member
    Join Date
    Jan 2009
    Posts
    671
    Rep Power
    6

    Default

    It looks to me like you just have the sense of 'bridge' backward, but that it nonetheless does what you want it to do. Is the answer not always '1000' and '2000' ? It looks to me like it should be, which proves that synchronization actually works.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •