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);
} }
}
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);
} }
}
{
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();
}
}
不过这种应该不算死锁的现象吧。
最终TestThread.flag == 2,Demo1在做没输出的死循环