黑马程序员技术交流社区
标题:
复习一下死锁
[打印本页]
作者:
冷冷丶丶
时间:
2014-9-18 10:49
标题:
复习一下死锁
class MyLock{
static Object locka = new Object();
static Object lockb = new Object();
}
class Test2 implements Runnable{
private boolean flag;
Test2(boolean flag){
this.flag = flag;
}
public void run(){
if(flag){
while(true){
synchronized(MyLock.locka){
System.out.println("if locka");
synchronized(MyLock.lockb){
System.out.println("if lockb");
}
}
}
}
else{
while(true){
synchronized(MyLock.lockb){
System.out.println("if lockb");
synchronized(MyLock.locka){
System.out.println("if locka");
}
}
}
}
}
}
public class DeadLockTest {
public static void main(String[] args) {
Thread t1 = new Thread(new Test2(true));
Thread t2 = new Thread(new Test2(false));
t1.start();
t2.start();
}
}
死锁:同步中嵌套同步
作者:
不系之舟王
时间:
2014-9-18 11:06
哎!多线程感觉好难啊
作者:
家进
时间:
2014-9-18 11:37
楼主把 locka和lockb 的静态属性去掉看看,结果会不一样哦。
例如我改成下面那样,为什么会没有出现死锁的情况?我也想知道原因。
class MyLock
{
private final Object locka = new Object();
private final Object lockb = new Object();
public Object getloka()
{
return locka;
}
public Object getlokb()
{
return lockb;
}
}
class Test2 implements Runnable{
MyLock m = new MyLock();
private boolean flag;
Test2(boolean flag){
this.flag = flag;
}
public void run(){
if(flag){
while(true){
synchronized(m.getloka()){
System.out.println("if locka");
synchronized(m.getlokb()){
System.out.println("if lockb");
}
}
}
}
else{
while(true){
synchronized(m.getlokb()){
System.out.println("if lockb");
synchronized(m.getloka()){
System.out.println("if locka");
}
}
}
}
}
}
public class DeadLockTest {
public static void main(String[] args) {
Thread t1 = new Thread(new Test2(true));
Thread t2 = new Thread(new Test2(false));
t1.start();
t2.start();
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2