Examples of MyLock


Examples of com.packtpub.java7.concurrency.chapter7.recipe08.task.MyLock

  public static void main(String[] args) {

    /*
     * Create a new MyLock object
     */
    MyLock lock=new MyLock();
   
    /*
     * Create and run ten task objects
     */
    for (int i=0; i<10; i++){
      Task task=new Task("Task-"+i,lock);
      Thread thread=new Thread(task);
      thread.start();
    }
   
    /*
     * The main thread also tries to get the lock
     */
    boolean value;
    do {
      try {
        value=lock.tryLock(1,TimeUnit.SECONDS);
        if (!value) {
          System.out.printf("Main: Trying to get the Lock\n");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
        value=false;
      }
    } while (!value);
   
    /*
     * The main thread release the lock
     */
    System.out.printf("Main: Got the lock\n");
    lock.unlock();
   
    /*
     * Write a message in the console indicating the end of the program
     */
    System.out.printf("Main: End of the program\n");
View Full Code Here

Examples of com.packtpub.java7.concurrency.chapter8.recipe02.task.MyLock

   */
  public static void main(String[] args) throws Exception {
    /*
     * Create a Lock object
     */
    MyLock lock=new MyLock();
   
    /*
     * Create an array for five threads
     */
    Thread threads[]=new Thread[5];
   
    /*
     * Create and start five threads
     */
    for (int i=0; i<5; i++) {
      Task task=new Task(lock);
      threads[i]=new Thread(task);
      threads[i].start();
    }
   
    /*
     * Create a loop with 15 steps
     */
    for (int i=0; i<15; i++) {
      /*
       * Write info about the lock
       */
      System.out.printf("Main: Logging the Lock\n");
      System.out.printf("************************\n");
      System.out.printf("Lock: Owner : %s\n",lock.getOwnerName());
      System.out.printf("Lock: Queued Threads: %s\n",lock.hasQueuedThreads());
      if (lock.hasQueuedThreads()){
        System.out.printf("Lock: Queue Length: %d\n",lock.getQueueLength());
        System.out.printf("Lock: Queued Threads: ");
        Collection<Thread> lockedThreads=lock.getThreads();
        for (Thread lockedThread : lockedThreads) {
        System.out.printf("%s ",lockedThread.getName());
        }
        System.out.printf("\n");
      }
      System.out.printf("Lock: Fairness: %s\n",lock.isFair());
      System.out.printf("Lock: Locked: %s\n",lock.isLocked());
      System.out.printf("************************\n");
      /*
       * Sleep the thread for one second
       */
      TimeUnit.SECONDS.sleep(1);
 
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.