Yurttas/PL/OOL/Java/F/07/03/T01.java

From ZCubes Wiki
Jump to navigation Jump to search
  1/**
  2 *  Copyright(C) 1998
  3 *  All Rights Reserved. Salih Yurttas, ZCubes, BitsOfCode Software Systems, Inc..
  4 *
  5 *  Permission to use, copy, modify, and distribute this
  6 *  software and its documentation for EDUCATIONAL purposes
  7 *  and without fee is hereby granted provided that this
  8 *  copyright notice appears in all copies.
  9 *
 10 *  @date   : January 1, 1998.
 11 *  @author : Salih Yurttas.
 12 */
 13
 14
 15public class T01 {
 16
 17  private String sid;
 18
 19  public T01(String id) {
 20    sid=id;
 21  }
 22
 23  public static void threadPrint(String msg) {
 24    String threadName = Thread.currentThread().getName();
 25    System.out.println(threadName+
 26                       msg);
 27  }
 28
 29  public synchronized void checkOther(T01 other) {
 30    threadPrint("Entered checkOther");
 31
 32    try {
 33      Thread.sleep(2000);
 34    }
 35    catch(InterruptedException iE) {}
 36
 37    threadPrint("in checkOther() - about to invoke other.action()");
 38    other.action();
 39    threadPrint("Leaving checkOther");
 40  }
 41
 42  public synchronized void action() {
 43    threadPrint("Entering action");
 44
 45    try {
 46      Thread.sleep(500);
 47    }
 48    catch(InterruptedException iE) {}
 49
 50    threadPrint(" Leaving action");
 51  }
 52
 53  public static void main(String[] args){
 54    final T01 o1 = new T01("o1");
 55    final T01 o2 = new T01("o2");
 56
 57    Runnable runA= new Runnable() {
 58      public void run() {
 59        o1.checkOther(o2);
 60      }
 61    };
 62
 63    Thread threadA = new Thread(runA,
 64                                "threadA");
 65    threadA.start();
 66
 67    try {
 68      Thread.sleep(200);
 69    }
 70    catch(InterruptedException iE) {}
 71
 72    Runnable runB= new Runnable() {
 73      public void run() {
 74        o2.checkOther(o1);
 75      }
 76    };
 77
 78    Thread threadB = new Thread(runB,
 79                                "threadB");
 80    threadB.start();
 81
 82    try {
 83      Thread.sleep(5000);
 84    }
 85    catch(InterruptedException iE) {}
 86  
 87    threadPrint("finished Thread.sleeping");
 88    threadPrint("About to interrupt threadA");
 89
 90    threadA.interrupt();
 91
 92    try {
 93      Thread.sleep(1000);
 94    }
 95    catch(InterruptedException iE) {}
 96  
 97    threadPrint(" finished Thread.sleeping");
 98    threadPrint(" About to interrupt threadB");
 99    threadB.interrupt();
100
101    try {
102      Thread.sleep(1000);
103    }
104    catch(InterruptedException iE) {}
105
106    threadPrint(" System is deadlocked");
107  }
108
109}