死锁(面试常考)
来源:互联网 发布:matlab 矩阵色块图 编辑:程序博客网 时间:2024/06/05 01:13
//死锁之static关键字的作用
public class TestDeadLock implements Runnable {
int flag = 0;
static Object t1 = new Object();//这个地方的static一定不能少 因为这里是成员变量的位置 如果不加static 那么每当你new一个TestDeadLock
static Object t2 = new Object();//对象出来时 就会同时在heap里面出现t1跟t2 这样根本锁不住
public static void main(String[] args) {
TestDeadLock one = new TestDeadLock();//如果没有static 那么heap会有两队t1跟t2 达不到死锁的目的
TestDeadLock two = new TestDeadLock();//画一下内存分布图就明白了
Thread one1 = new Thread(one);
Thread two2 = new Thread(two);
one.flag = 1;
two.flag = 0;
one1.start();
two2.start();
}
public void run() {
System.out.println("flag=="+flag);
if(flag == 0) {
synchronized (t1) {
try {
Thread.sleep(5000);
} catch(Exception e) {
return ;
}
synchronized (t2) {
System.out.println("ok");
}
}
}
if(flag == 1) {
synchronized (t2) {
try {
Thread.sleep(5000);
} catch(Exception e) {
return ;
}
synchronized (t1) {
System.out.println("ok");
}
}
}
}
}
public class TestDeadLock implements Runnable {
int flag = 0;
static Object t1 = new Object();//这个地方的static一定不能少 因为这里是成员变量的位置 如果不加static 那么每当你new一个TestDeadLock
static Object t2 = new Object();//对象出来时 就会同时在heap里面出现t1跟t2 这样根本锁不住
public static void main(String[] args) {
TestDeadLock one = new TestDeadLock();//如果没有static 那么heap会有两队t1跟t2 达不到死锁的目的
TestDeadLock two = new TestDeadLock();//画一下内存分布图就明白了
Thread one1 = new Thread(one);
Thread two2 = new Thread(two);
one.flag = 1;
two.flag = 0;
one1.start();
two2.start();
}
public void run() {
System.out.println("flag=="+flag);
if(flag == 0) {
synchronized (t1) {
try {
Thread.sleep(5000);
} catch(Exception e) {
return ;
}
synchronized (t2) {
System.out.println("ok");
}
}
}
if(flag == 1) {
synchronized (t2) {
try {
Thread.sleep(5000);
} catch(Exception e) {
return ;
}
synchronized (t1) {
System.out.println("ok");
}
}
}
}
}
0 0
- 死锁(面试常考)
- 面试专题-----计算机网络常考(一)
- 面试专题-----计算机网络常考(二)
- 面试专题-----计算机网络常考(三)
- 面试专题-----计算机网络常考(四)
- 面试专题-----计算机网络常考(五)
- 面试专题-----计算机网络常考(六)
- 面试专题-----计算机网络常考(七)
- 面试专题-----操作系统常考(一)
- servlet面试常考
- 计算机网络面试常考
- 面试常考
- 面试常考知识
- 面试常考排序
- 面试常考智力题
- 一些面试常考知识点
- 操作系统常考面试题目
- 计算机网络之面试常考
- Ubuntu15安装IDEA开发工具
- 动态生成行,序号随之增加,删除后依然按顺序。所以给动态生成的html元素绑定click事件
- 1.1输出一行文字
- JVM系列二:GC策略&内存申请、对象衰老
- PKU 2777 Count Color
- 死锁(面试常考)
- Java 面试——基础程序题001
- 506. Relative Ranks
- 【网络】TCP三次握手四次挥手
- 华为机试-字符串排序
- C++第一次实验项目3、5(二)
- 死锁面试真题
- PBC library 学习笔记(二)
- Linux是什么?