zoukankan      html  css  js  c++  java
  • JAVA_Thread_deadlock

    package com.kk.thread;
    /*
    * 本类演示死锁的形成
    * 基本数据类型是不能作为同步块的参考,例:int b;synchronized(b)
    */
    public class TicketsSystem {

    public static void main(String[] args)throws Exception {
    SellThread sell=new SellThread();
    new Thread(sell).start();
    Thread.sleep(1);//让thread1执行,此时b=false;
    sell.b=true;
    new Thread(sell).start();
    }

    }

    class SellThread implements Runnable{

    int tickets=1000;
    Object obj=new Object();
    boolean b=false;
    public void run() {
    if (b) {
    sell();
    }else{
    synchronized(obj){ //将obj锁住
    while(true){
    if (tickets>0) {
    try {
    Thread.currentThread().sleep(10);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    synchronized(this){ //按照本程序的执行顺序,此时this已经被sell方法锁住
    System.out.println("obj___"+Thread.currentThread().getName()+"__"+tickets);
    tickets--;
    }
    }
    }
    }
    }
    }

    /*
    * 同步方法会给类的实例加锁(this)
    * 静态同步方法会给类加锁(Class)
    */
    private synchronized void sell(){ //将类的实例锁住(this)
    while(true){
    if (tickets>0) {
    try {
    Thread.currentThread().sleep(10);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    synchronized(obj){ //等线程苏醒,obj已经被run方法中的synchronized(obj)锁住
    System.out.println("this___"+Thread.currentThread().getName()+"__"+tickets);
    tickets--;
    }
    }
    }
    }

    }
  • 相关阅读:
    Welcome-to-Swift-12附属脚本(Subscripts)
    Summarization of Tech Interviews
    How to Conduct High-Impact Research and Produce High-Quality Papers
    ZVAL——PHP源码分析
    个人使命
    习题-机器学习-西瓜书-周志华
    Machine Learning
    《踏踏实实学英语》读书笔记
    TF-IDF原理与实现
    线性代数学习感悟
  • 原文地址:https://www.cnblogs.com/BigIdiot/p/2290519.html
Copyright © 2011-2022 走看看