class Test
{
private boolean flag;
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 locka");
}
}
}
}
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();
}
}
除了用boolean语句切换线程 还可以用什么方式切换呢?
|
|