zoukankan      html  css  js  c++  java
  • Java基础面试操作题: 线程问题,写一个死锁(原理:只有互相都等待对方放弃资源才会产生死锁)

    package com.swift;
    
    public class DeadLock implements Runnable {
        private boolean flag;
    
        DeadLock(boolean flag) {
            this.flag = flag;
        }
    
        public void run() {
            while (true) {
                if (flag) {
                    synchronized ("suo1") {
                        System.out.println(Thread.currentThread().getName()+"if....locka");
                        synchronized ("suo2") {
                            System.out.println(Thread.currentThread().getName()+"if.....lockb");
                        }
                    }
                } else {
                    synchronized ("suo2") {
                        System.out.println(Thread.currentThread().getName()+"else.....lockb");
                        synchronized ("suo1") {
                            System.out.println(Thread.currentThread().getName()+"else....locka");
                        }
                    }
                }
            }
        }
    
        public static void main(String[] args) {
            
            /*
             * 写一个死锁
             */
            //只有互相都等待对方放弃资源才会产生死锁
            new Thread(new DeadLock(true),"线程1").start();
            new Thread(new DeadLock(false),"线程2").start();
        }
    }

    同步代码块的锁也可以用对象,如LockA.locka

    locka对象为静态 公共

  • 相关阅读:
    分解质因数
    大素数测试和分解质因数
    快速幂
    欧拉函数
    素数
    gcd,lcm,ext_gcd,inv
    凸包问题 poj 2187
    map的 简单用法
    判断线段是否在园内
    2-sat 问题
  • 原文地址:https://www.cnblogs.com/qingyundian/p/8318367.html
Copyright © 2011-2022 走看看