package com.dq;
public class ThreadTest implements Runnable
{
// 2个对象代表2把锁
Object obj1 = new Object();
Object obj2 = new Object();
@Override
public void run()
{
if(Thread.currentThread().getName().equals("thread1"))
{
synchronized (obj1)
{
System.out.println("得到obj1,准备进入obj2锁方法块");
try
{
Thread.sleep(20); //休眠的目的是为了让另一个线程获得执行机会得到另一把锁
}
catch (InterruptedException e)
{
e.printStackTrace();
}
synchronized (obj2)
{
System.out.println("线程1进入obj2方法块");
}
}
}
else
{
synchronized (obj2)
{
System.out.println("得到obj2,准备进入obj1锁方法块");
try
{
Thread.sleep(20);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
synchronized (obj1)
{
System.out.println("线程2进入obj1方法块");
}
}
}
}
public static void main(String[] args)
{
ThreadTest task = new ThreadTest();
Thread thread1 = new Thread(task,"thread1");
Thread thread2 = new Thread(task,"thread2");
thread1.start();
thread2.start();
}
}
死锁的示例代码
猜你喜欢
转载自blog.csdn.net/gunsmoke/article/details/104714955
今日推荐
周排行