- /*
- 写一个死锁程序
- */
-
- //定义一个类来实现Runnable,并复写run方法
- class LockTest implements Runnable
- {
- private boolean flag;
- LockTest(boolean flag)
- {
- this.flag=flag;
- }
- public void run()
- {
- if(flag)
- {
- while(true)
- {
- synchronized(LockClass.locka)//a锁
- {
- System.out.println(Thread.currentThread().getName()+"------if_locka");
-
- synchronized(LockClass.lockb)//b锁
- {
- System.out.println(Thread.currentThread().getName()+"------if_lockb");
- }
- }
- }
- }
- else
- {
- while(true)
- {
- synchronized(LockClass.lockb)//b锁
- {
- System.out.println(Thread.currentThread().getName()+"------else_lockb");
-
- synchronized(LockClass.locka)//a锁
- {
- System.out.println(Thread.currentThread().getName()+"------else_locka");
- }
- }
- }
- }
- }
- }
-
- //定义两个锁
- class LockClass
- {
- static Object locka = new Object();
- static Object lockb = new Object();
- }
-
- class DeadLock
- {
- public static void main(String[] args)
- {
- //创建2个进程,并启动
- new Thread(new LockTest(true)).start();
- new Thread(new LockTest(false)).start();
- }
- }
|
|