zoukankan      html  css  js  c++  java
  • 线程死锁示例

    线程死锁:

     1 package com.iotek.synchronizedtest;
     2 
     3 public class DeadThread {
     4 
     5     /**
     6      * 线程死锁示例
     7      * 相互等待锁的释放,导致死锁,应避免同步块里面出现锁的嵌套!!!
     8      * @param args
     9      */
    10     public static void main(String[] args) {
    11         Example example = new Example();
    12         DieThread1 thread1 = new DieThread1(example);
    13         thread1.start();
    14         DieThread2 thread2 = new DieThread2(example);
    15         thread2.start();
    16         
    17     }
    18 
    19 }
    20 
    21 class DieThread1 extends Thread {
    22     private Example example = null;
    23 
    24     public DieThread1(Example example) {
    25         super();
    26         this.example = example;
    27     }
    28 
    29     @Override
    30     public void run() {
    31         example.method1();
    32     }
    33 }
    34 
    35 class DieThread2 extends Thread {
    36     private Example example = null;
    37 
    38     public DieThread2(Example example) {
    39         super();
    40         this.example = example;
    41     }
    42 
    43     @Override
    44     public void run() {
    45         example.method2();
    46     }
    47 }
    48 
    49 class Example {
    50     private Object obj1 = new Object();
    51     private Object obj2 = new Object();
    52 
    53     public void method1() {
    54         synchronized (obj1) {
    55             // 同步代码块,获取对象obj1的锁
    56             try {
    57                 Thread.sleep(1000); // 线程等待
    58             } catch (InterruptedException e) {
    59                 e.printStackTrace();
    60             }
    61             synchronized (obj2) {
    62                 // 获取对象obj1的锁的同时,获取obj2的锁
    63                 System.out.println("method1");
    64             }
    65         }
    66     }
    67 
    68     public void method2() {
    69         synchronized (obj2) {
    70             // 同步代码块,获取对象obj2的锁
    71             try {
    72                 Thread.sleep(1000); // 线程等待
    73             } catch (InterruptedException e) {
    74                 e.printStackTrace();
    75             }
    76             synchronized (obj1) {
    77                 // 获取对象obj2的锁的同时,获取obj1的锁
    78                 System.out.println("method2");
    79             }
    80         }
    81     }
    82 
    83 }
  • 相关阅读:
    故事讲的好,才会有人去思考:什么是成功的商业片——记《疯狂的石头》
    收集的特色flash网站
    pf负载均衡
    squid故障与解决方法汇总
    IIS7.0在Vista上的错误 0x80070021
    PF 默认会限制最大连接数5000问题
    Squid日志详解
    samba结合AD实现大型网络方案
    inotify监听+rsync
    AD帐号登陆samba自动创建主目录脚本
  • 原文地址:https://www.cnblogs.com/enjoyjava/p/8192661.html
Copyright © 2011-2022 走看看