本帖最后由 ily521125 于 2014-8-1 17:50 编辑
- /*
- 死锁:
- 同步中嵌套同步
- 如:在多线程中,线程一中locka锁嵌套lockb锁,线程二中lockb锁嵌套locka锁,会发生死锁
- 注:locka lockb为锁对象
- */
- class Test implements Runnable
- {
- private boolean flag;
- Test(boolean flag)
- {
- this.flag=flag;
- }
- public void run()
- {
- if(flag)
- {
- synchronized(MyLock.locka) //锁对象为locka
- {
- System.out.println(Thread.currentThread().getName()+"...if locka");
- synchronized(MyLock.lockb) //锁对象为lockb
- {
- System.out.println(Thread.currentThread().getName()+"...if lockb");
- }
- }
- }
- else
- {
- synchronized(MyLock.lockb) //锁对象为lockb
- {
- System.out.println(Thread.currentThread().getName()+"...if lockb");
- synchronized(MyLock.locka) //锁对象为locka
- {
- System.out.println(Thread.currentThread().getName()+"...if locka");
- }
- }
- }
- }
- }
- class MyLock
- {
- //创建两个Object对象
- 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(); //启动线程二
- }
- }
复制代码
|