package com.zdyn.action;public class TestThread { public static int flag = 1; public static void main(String[] args) {
Thread t1 = new Thread(new Demo1());
Thread t2 = new Thread(new Demo2());
t1.start();
t2.start();
}
}class Demo1 implements Runnable { public void run() { while (true) {
if (TestThread.flag == 1) { System.out.println(TestThread.flag = 2); }
}
}}class Demo2 implements Runnable { public void run() { if (TestThread.flag == 2) { System.out.println(TestThread.flag = 1);
} }
}

解决方案 »

  1.   

    你把frag初始化为0是不是就算死锁了···
      

  2.   

    感觉不算 给LZ写了个死锁仅供LZ参考class Test implements Runnable
    {
    private boolean flag; public Test(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("else lockb");
    synchronized(MyLock.locka)
    {
    System.out.println("else locka");
    }
    }
    }
    }
    }
    }class MyLock
    {
    static Object locka = new Object();
    static Object lockb = new Object();
    }class  DeadLockTest
    {
    public static void main(String[] args) 
    {
    Thread t1 = new Thread(new Test(true));
    Thread t2 = new Thread(new Test(false)); t1.start();
    t2.start();
    }
    }
      

  3.   

    额你的代码和死锁完全没关系,一般同步的时候才会引起死锁,比如线程One完成一个任务需要A的锁,自己此时有B的锁拿着不放,而线程Two完成一个任务需要B的锁,而自己拿着A的锁不放。这时候当2个人都不肯释放对方需要的锁的时候就会生产死锁。
      

  4.   

    虽然第二个线程只执行一次就结束了,无法再给线程1设置flag,导致线程1无法进入if()语句
    不过这种应该不算死锁的现象吧。
      

  5.   

    不是,你Demo2的run执行完了, 
    最终TestThread.flag == 2,Demo1在做没输出的死循环