zoukankan      html  css  js  c++  java
  • java 张三和李四的死锁

     1 class ZhangSan{
    2 public void say(){
    3 System.out.println("Zhang said:you should lend your painting to me!");
    4 }
    5 public void get(){
    6 System.out.println("Zhang has got it!");
    7 }
    8 }
    9 class LiSi{
    10 public void say(){
    11 System.out.println("Li said:you should lend your book to me!");
    12 }
    13 public void get(){
    14 System.out.println("Li has got it!");
    15 }
    16 }
    17 public class DeadLock implements Runnable{
    18 private static ZhangSan zs=new ZhangSan();
    19 private static LiSi ls=new LiSi();
    20 private boolean flag=false;
    21 public void run(){
    22 if(flag){
    23 synchronized (zs){
    24 zs.say();
    25 try{
    26 Thread.sleep(500);
    27 }catch (InterruptedException e){
    28 e.printStackTrace();
    29 }
    30 synchronized (ls){
    31 zs.get();
    32 }
    33 }
    34 }else{
    35 synchronized (ls){
    36 ls.say();
    37 try{
    38 Thread.sleep(500);
    39 }catch (InterruptedException e){
    40 e.printStackTrace();
    41 }
    42 synchronized (zs){
    43 ls.get();
    44 }
    45 }
    46 }
    47 }
    48 public static void main(String[] args) {
    49 DeadLock t1=new DeadLock();
    50 DeadLock t2=new DeadLock();
    51 t1.flag=true;
    52 t2.flag=false;
    53 Thread thA=new Thread(t1);
    54 Thread thB=new Thread(t2);
    55 thA.start();
    56 thB.start();
    57 }
    58 }

    从程序中可以看出,两个线程都在等待彼此执行完成,从而死锁。。

  • 相关阅读:
    Oracle to_char格式化函数
    电脑快捷键大全
    Failed to create the Java Virtual Machine (Myeclipse或者eclipse启动报错)
    Java 面试题
    UVA1108 Mining Your Own Business
    无向图的连通性
    [NOI Online #2 提高组]子序列问题
    [NOI Online #3 提高组]优秀子序列
    POJ2430 Lazy Cows
    UVA1633 Dyslexic Gollum
  • 原文地址:https://www.cnblogs.com/dennisac/p/2394375.html
Copyright © 2011-2022 走看看