产生死锁的原因是A锁和B锁互相等待,直接上代码- package test;
- class Lock
- {
- public static void main(String[] args)
- {
- PersonA p1 = new PersonA("林青霞",20,1);
- PersonA p2 = new PersonA("麦蒂",40,0);
- Thread t1 = new Thread(p1);
- Thread t2 = new Thread(p2);
- t1.start();
- t2.start();
- t1.run();
- t2.run();
- }
- }
- class PersonA implements Runnable
- {
- //可以定义两个锁,为了保证唯一性这里定义为静态
- static String a = new String("A锁");
- static String b = new String("B锁");
- String name;
- int age;
- int sexual;//0代表男人,1代表女人
- public PersonA(String name,int age,int sexual)
- {
- this.name=name;
- this.age=age;
- this.sexual=sexual;
- }
- public void run()
- {
- while (true)
- {
- if (sexual>0)
- {
- synchronized(a)//t1进来上了a锁,
- {
- {
- System.out.print("女人***");
- }
- synchronized(b)//此时b锁已被t2上了,就进不去了所以t1卡在这里
- {
- {
- System.out.print(this.name);
- System.out.print("--");
- System.out.println(this.age);
- }
- }
- }
-
-
- }
- else
- {
- synchronized(b)//t2进来上了b锁,
- {
- {
- System.out.print("男人***");
- }
- synchronized(a)//此时a锁已被t1上了,就进不去了所以t2卡在这里;于是互相卡住
- {
- {
- System.out.print(this.name);
- System.out.print("--");
- System.out.println(this.age);
- }
- }
- }
-
-
- }
- }
-
- }
- }
复制代码 |