zoukankan      html  css  js  c++  java
  • 死锁必须synchronize套synchronize

    package com.Thread;
     
    public class DeathSynchronized {
           public static void main(String[] args) {
                 //资源
                Object g = new Object();
                Object m = new Object();
                 //创建线程
                Test1 t1 = new Test1(g,m);
                Test2 t2 = new Test2(g,m);
                Thread proxy = new Thread(t1);
                Thread proxy2 = new Thread(t2);
                 //启动线程
                proxy.start();
                proxy2.start();
          }
    }
     
    class Test1 implements Runnable {
          Object goods ;
          Object money ;
           public Test1(Object goods, Object money) {
                 this.goods = goods;
                 this.money = money;
          }
     
           @Override
           public void run() {
                 while(true ) {
                       try {
                            test();
                      } catch (Exception e) {
                            e.printStackTrace();
                      }
                }
          }
          
           public void test(){
                 synchronized(goods ){
                       try {
                            Thread. sleep(1000);
                      } catch (InterruptedException e) {
                            e.printStackTrace();
                      }
                       synchronized(money ){
                      }
                      System. out.println("一挥手交钱、、、、" );
                }
          }
          
    }
    class Test2 implements Runnable {
          Object goods ;
          Object money ;
           public Test2(Object goods, Object money) {
                 this.goods = goods;
                 this.money = money;
          }
     
           @Override
           public void run() {
                 while(true ) {
                       try {
                             test();
                      } catch (Exception e) {
                            e.printStackTrace();
                      }
                }
          }
          
           public void test (){
                 synchronized(money ){
                       try {
                            Thread. sleep(5000);
                      } catch (InterruptedException e) {
                            e.printStackTrace();
                      }
                       synchronized(goods ){
                            
                      }
                      System. out.println("一挥手交huo、、、、" );
                }
          }
          
    }
  • 相关阅读:
    功能工作第五天终于有点眉目了
    SSM上传图片并保存图片地址到数据库
    基于Maven搭建SSM框架eclipese版本
    菜鸟初到公司应该准备的开发环境
    IDEA+Maven+SSM框架实现的简单的增、删、改、查
    如何在IDEA 中使用Git
    maven-ssm项目整合
    关于线程的知识模块
    百度地图api,使用QT同时绘制多个标注
    win10系统QT5下配置opencv教程
  • 原文地址:https://www.cnblogs.com/king-/p/4389732.html
Copyright © 2011-2022 走看看