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

     Java多线程使用synchronized 锁时,可能会出现死锁;死锁会导致两个线程无限等待,致使程序异常。因此使用synchronized 关键字时注意死锁的问题。

    笔者在第一次运行程序的时候属性 A=“a”、B=“a”,并没有引起死锁的问题;原因很简单,这时A 和 B的地址是一样的,synchronized 认为是同一个对象资源,不会对对象A 和 B同时加锁。

    引起死锁的例子: 

    public class DeadLock {

     private String A = "a";
    private String B = "b";
    @SuppressWarnings("static-access")
    public void deadLock(){
    Thread thread1 = new Thread(new Runnable(){
    @Override
    public void run() {
    System.out.println("thread1-start");
    synchronized (A) {
    System.out.println("1" + A);
    try {
    Thread.currentThread().sleep(2000);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    synchronized (B){
    System.out.println("2" + B);
    }
    }
    System.out.println("thread1-end");
    }
    });
    Thread thread2 = new Thread(new Runnable(){
    @Override
    public void run() {
    System.out.println("thread2-start");
    synchronized (B) {
    System.out.println("3" + B);
    synchronized (A){
    System.out.println("4" + A);
    }
    }
    System.out.println("thread2-end");
    }
    });
    thread1.start();
    thread2.start();
    }
    public static void main(String[] args){
        
    new DeadLock().deadLock();
    }
    }
    不积跬步无以至千里,不积小流无以成江河
  • 相关阅读:
    HTML常用标签
    JSP是什么?
    Linux下叹号!的用法
    原码、反码、补码、移码之间的关系和转换
    关于联想超极本出现蓝屏Default Boot Device Missing or Boot Failed的解决办法
    基于UEFI和GPT模式下U盘安装windows8.1和Linux双启动教程
    horizon服务
    neutron网络服务部署
    neutron网络服务
    cinder存储服务
  • 原文地址:https://www.cnblogs.com/lyxb/p/7325165.html
Copyright © 2011-2022 走看看