死锁示例程序
来源:互联网 发布:mac上pdf软件 编辑:程序博客网 时间:2024/06/09 19:15
public class deadlock {/**一个简单的死锁类 * 在一个Runnable实现类中模拟两个进程的执行内容; * 当flag == true时模块1(线程1)执行,先执行锁外程序(不受锁限制),再锁定锁1 * (str对象)执行100到1的输出, * 然后锁定锁2(str1对象),即需要得到锁2才能继续执行; * 当flag == false时模块2(线程2)执行,先锁定锁2(str1对象)执行1到100的输出, * 然后锁定锁1(str对象),即需要得到锁1才能继续执行; * 所以此时两个线程互相等待对方释放手里的锁,导致程序阻塞,造成死锁。 */public static void main(String[] args) {// TODO 自动生成方法存根deadtest tt0 = new deadtest();// TxtThread tt1 = new TxtThread();// TxtThread tt2 = new TxtThread();// TxtThread tt3 = new TxtThread();tt0.flag = false;new Thread(tt0).start();deadtest tt1 = new deadtest();tt1.flag = true;new Thread(tt1).start();// new Thread(tt0).start();// new Thread(tt0).start();// new Thread(tt1).start();// new Thread(tt2).start();// new Thread(tt3).start();}}class deadtest implements Runnable {static String str = new String();static String str2 = new String();boolean flag;public void run() {if (flag == true) {for (int i = 1; i <= 20; i++) {try {Thread.sleep(10);} catch (Exception e) {e.getMessage();}System.out.println("鎖之外");}synchronized (str) {int num = 100;while (num > 0) {try {Thread.sleep(10);} catch (Exception e) {e.getMessage();}System.out.println(Thread.currentThread().getName()+ "this is 模块1锁1 " + num--);}synchronized (str2) {int num2 = 100;for (int j = 0; j <= num2; j++) {try {Thread.sleep(10);} catch (Exception e) {e.getMessage();}System.out.println(Thread.currentThread().getName()+ "this is 模块1锁2 " + j);}}}}if (flag == false) {synchronized (str2) {int num2 = 100;for (int j = 0; j <= num2; j++) {try {Thread.sleep(10);} catch (Exception e) {e.getMessage();}System.out.println(Thread.currentThread().getName()+ "this is 模块2锁2 " + j);}synchronized (str) {int num = 100;while (num > 0) {try {Thread.sleep(10);} catch (Exception e) {e.getMessage();}System.out.println(Thread.currentThread().getName()+ "this is模块2锁1 " + num--);}}}}}}
0 0
- 死锁示例程序
- 死锁示例
- 死锁程序
- 多线程---死锁示例
- Java基础:死锁示例
- mysql死锁示例
- java死锁代码示例
- JavaSE 多线程 死锁示例
- 进程同步-死锁示例
- java的死锁示例
- 死锁,Java简单示例
- Java死锁代码示例
- 导致死锁的SQL示例
- 一个简单的死锁示例
- 嵌入式 GDB调试死锁示例
- Java实现的死锁示例
- Java死锁示例及检测
- 查找死锁程序
- string::substr
- 初学Zynq与Vivado
- 【HiveETL】物流行业 -- 订单跟踪、SLA
- Android自定义View(二)
- Linux/UNIX 定时任务 cron 详解
- 死锁示例程序
- Java基础之(一) 变量
- zookeeper轻松入门
- wait notify notifyAll
- Program4_F
- leetcode 88 Merge Sorted Array
- libuv学习笔记(18)
- ThreadPoolExecutor原理与使用
- java获取项目访问路径的方法