- Thread t1 = new Thread(new Test(true),"1号");
- Thread t2 = new Thread(new Test(false),"2号");
- t1.start();
- t2.start();
你这里建了俩 对象。。。。里面的flag,锁啥的都不共享。。。。。
传一个对象进去就欧了
给你改了改代码 加个循环
- class Test implements Runnable{
- private boolean flag=true;
- Object obj1 = new Object();
- Object obj2 = new Object();
-
- public void run()
- {
- while(true)
- {
- if(flag)
- {
- synchronized(obj1)
- {
- System.out.println(Thread.currentThread().getName()+" if---obj1");
- synchronized(obj2)
- {
- System.out.println(Thread.currentThread().getName()+" if---obj2");
- }
- }
- flag=false;
- }
- else
- {
- synchronized(obj2)
- {
- System.out.println(Thread.currentThread().getName()+" else---obj2");
- synchronized(obj1)
- {
- System.out.println(Thread.currentThread().getName()+" else---obj1");
- }
- }
- flag=true;
- }
- }
- }
- }
- class DeadLockTest {
- public static void main(String[] args) {
- Test test=new Test();
- Thread t1 = new Thread(test,"1号");
- Thread t2 = new Thread(test,"2号");
- t1.start();
- t2.start();
- }
- }
复制代码 |