Java, eksempel (køing)

class TakeResource {
   public static void main (String argv[]) {
      Resource resource = new Resource();
      User[] user = new User[3];
      user[0] = new User ("A  ", resource);
      try {Thread.sleep(1000);} 
         catch (InterruptedException e){}
      user[1] = new User (" B ", resource); // Stakkars meg!
      try {Thread.sleep(1000);} 
         catch (InterruptedException e){}
      user[2] = new User ("  C", resource);
   }
}

class Resource {
   public synchronized void take (String id) {
      System.out.println ("User " + id + " has resource");
      try {Thread.sleep(3000);} 
         catch (InterruptedException e){}
   }
}

class User extends Thread {
   private String id;
   private Resource resource;

   public User (String id, Resource resource) {
      this.id = id;
      this.resource = resource;
      System.out.println ("User " + id + " started");
      start();
   }

   public void run() {
      while (true) {
         resource.take(id);
         try {Thread.sleep(1000);}
            catch (InterruptedException e){}
      }
   }
}

[1]


ï &