JAVA_Thread_deadlock
2024-06-01 14:38:55
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--; } } } } }
转载于:https://www.cnblogs.com/BigIdiot/archive/2011/12/16/2290519.html
JAVA_Thread_deadlock相关推荐
最新文章
- Nagios之事件处理
- Power BI for Office 365(七) Power BI站点
- 平衡二叉树及其操作实现_平衡二叉树(AVL树)及C语言实现
- 绝望的力量:美术创作者的晋级之路
- 论文浅尝 | 基于知识图的问答变分推理
- 循环数组中找查找某个数值
- c语言qq聊天刷屏代码大全,QQ聊天刷屏脚本 达人分享技巧
- 以《数据安全法》为背景的全息数据安全解决方案
- 自增 ID 用完了怎么办 ?
- 家政维修小程序+上门预约小程序+VUE前后端分离+uniapp(附近师傅+门店入驻+在线抢单服务APP、小程序、公众号、H5)
- PTA-学生成绩录入及查询 zym广东外语外贸大学
- python爬虫学习-scrapy爬取链家房源信息并存储
- Flink报错:exceeded checkpoint tolerable failure threshould
- Samba服务器搭建与配置
- linux 查看文件创建时间
- 你应该知道的requestIdleCallback
- 基因对疾病的影响规律--读论文
- 聊聊C++任务定时器的设计与具体实现
- com.netflix.hystrix.exception.HystrixRuntimeException short-circuited and no fallback available
- Windows10安装ObjectARX 2021 Wizard无法创建项目的解决方案