Java deadlock生成的示例分析

发布时间:2021-11-20 17:58:46 作者:柒染
来源:亿速云 阅读:100

Java deadlock生成的示例分析,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

Java deadlock生成需要我们注意的关键点有很多,其实有不少的问题都能在源代码中寻找到不少的答案。下面我们就看看如何才能更好的做出Java deadlock生成。

public class Deadlock extends Object ...{  private String objID;  public Deadlock(String id) ...{  objID = id;  }  public synchronized void checkOther(Deadlock other) ...{  print("entering checkOther()");  // simulate some lengthy process  try ...{  Thread.sleep(2000);  } catch (InterruptedException x) ...{  }  print("in checkOther() - about to " + "invoke 'other.action()'");  other.action();  print("leaving checkOther()");  }  public synchronized void action() ...{  print("entering action()");  // simulate some work here  try ...{  Thread.sleep(500);  } catch (InterruptedException x) ...{  }  print("leaving action()");  }  public void print(String msg) ...{  threadPrint("objID=" + objID + " - " + msg);  }  public static void threadPrint(String msg) ...{  String threadName = Thread.currentThread().getName();  System.out.println(threadName + ": " + msg);  }  public static void main(String[] args) ...{  final Deadlock obj1 = new Deadlock("obj1");  final Deadlock obj2 = new Deadlock("obj2");  Runnable runA = new Runnable() ...{  public void run() ...{  obj1.checkOther(obj2);  }  };  Thread threadA = new Thread(runA, "threadA");  threadA.start();  try ...{  Thread.sleep(200);  } catch (InterruptedException x) ...{  }  Runnable runB = new Runnable() ...{  public void run() ...{  obj2.checkOther(obj1);  }  };  Thread threadB = new Thread(runB, "threadB");  threadB.start();  try ...{  Thread.sleep(5000);  } catch (InterruptedException x) ...{  }  threadPrint("finished sleeping");  threadPrint("about to interrupt() threadA");  threadA.interrupt();  try ...{  Thread.sleep(1000);  } catch (InterruptedException x) ...{  }  threadPrint("about to interrupt() threadB");  threadB.interrupt();  try ...{  Thread.sleep(1000);  } catch (InterruptedException x) ...{  }  threadPrint("did that break the deadlock?");  }  }

以上就是对Java deadlock生成的详细介绍,希望大家能有所领悟。

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

推荐阅读:
  1. Java多线程死锁避免方法
  2. 程序员笔记|如何编写高性能的Java代码

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java deadlock

上一篇:如何用Java多线程在mail中创建Thread对象

下一篇:怎么搭建Mysql单机实例

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》