代码如下package synchron;public class Thread3 { class Inner { private void m4t1() { int i = 5; while(i-- > 0) { System.out.println(Thread.currentThread().getName() + " : Inner.m4t1()=" + i); try { Thread.sleep(500); } catch(InterruptedException ie) { } } } private void m4t2() { int i = 5; while(i-- > 0) { System.out.println(Thread.currentThread().getName() + " : Inner.m4t2()=" + i); try { Thread.sleep(500); } catch(InterruptedException ie) { } } } } private void m4t1(Inner inner) { synchronized(inner) { //使用对象锁 inner.m4t1(); } } private void m4t2(Inner inner) { inner.m4t2(); } public static void main(String[] args) { final Thread3 myt3 = new Thread3(); final Inner inner = myt3.new Inner(); Thread t1 = new Thread( new Runnable() {public void run() { myt3.m4t1(inner);} }, "t1"); Thread t2 = new Thread( new Runnable() {public void run() { myt3.m4t2(inner);} }, "t2"); t1.start(); t2.start(); } }输出如下t1 : Inner.m4t1()=4t2 : Inner.m4t2()=4t1 : Inner.m4t1()=3t2 : Inner.m4t2()=3t1 : Inner.m4t1()=2t2 : Inner.m4t2()=2t1 : Inner.m4t1()=1t2 : Inner.m4t2()=1t1 : Inner.m4t1()=0t2 : Inner.m4t2()=0对于在m4t1中的对象锁,我不是很理解, 传入m4t1(),m4t2()的是同一个inner对象,m4t1已经将对象inner锁住, 为什么t2还可以访问m4t2呢? 希望可以有大神详细解释一下, 谢谢
添加回答
举报
0/150
提交
取消