黑马程序员技术交流社区
标题:
为啥我这个死锁锁不住?
[打印本页]
作者:
daniel031699
时间:
2016-6-4 08:40
标题:
为啥我这个死锁锁不住?
package a0524;
class SynLock implements Runnable {
private boolean flag;
Object locka=new Object();
Object lockb=new Object();
public SynLock(boolean flag)
{
this.flag=flag;
}
@Override
public void run() {
// TODO Auto-generated method stub
if(flag)
{
while(true){
synchronized (locka) {
System.out.println(Thread.currentThread().getName()+"...if .......locka....");
synchronized (lockb) {
System.out.println(Thread.currentThread().getName()+"...if .......lockb....");
}
}
}
}else
{
while(true){
synchronized (lockb) {
System.out.println(Thread.currentThread().getName()+"...else .......lockb....");
synchronized (locka) {
System.out.println(Thread.currentThread().getName()+"...else .......locka....");
}
}
}
}
}
}
public class SynLockDemo1 {
public static void main(String []args )
{
SynLock l1=new SynLock(true);
SynLock l2=new SynLock(false);
Thread t1 =new Thread(l1);
Thread t2 =new Thread(l2);
t1.start();
t2.start();
}
}
作者:
红豆蓝
时间:
2016-6-4 11:46
SynLock l1=new SynLock(true);
SynLock l2=new SynLock(false);
这里创建了2个对象,在每个对象中分别创建了locka和lockb,不同的锁,只是名字相同
作者:
695010894
时间:
2016-6-4 21:19
Object locka=new Object();
Object lockb=new Object();
加上:
static final修饰,保证前后锁的唯一性
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2