本帖最后由 聪明叉 于 2014-11-18 21:06 编辑
这是我的完整代码- class Demo implements Runnable
- {
- private boolean flag;
- Object locka = new Object();
- Object lockb = new Object();
-
- public Demo(boolean flag)
- {
- this.flag = flag;
- }
- public void run()
- {
- if(flag)
- {
- while (true)
- {
- synchronized(this)
- {
- System.out.println("if locka");
- synchronized(locka)
- {
- System.out.println("if lockb");
- }
- }
- }
- }
- else
- {
- while(true)
- {
- synchronized(locka)
- {
- System.out.println("else lockb");
- synchronized(this)
- {
- System.out.println("else locka");
- }
- }
- }
- }
- }
- }
- class LockDemo
- {
- public static void main(String[] args)
- {
- Thread t1 = new Thread(new Demo(true));
- Thread t2 = new Thread(new Demo(false));
- t1.start();
- t2.start();
- }
- }
复制代码
|