• 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 }

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

  • 相关阅读:
    bootstrap的引用和注意事项
    css样式表的知识点总结
    数据去重宏脚本
    redis总结
    list对象中根据两个参数过滤数据
    dt常用类
    C#删除字符串最后一个字符的几种方法
    C#的split分割的举例
    数据库优化的几个注意点
    两种转换城市的方式
  • 原文地址:https://www.cnblogs.com/dennisac/p/2394375.html
Copyright © 2020-2023  润新知