问题描述
代码如下:public class SomeObj { public void print(int i){ System.out.println(Thread.currentThread().getName()+DateHelper.getNow()+ " " + i); try { wait(1000); } catch (InterruptedException e) { e.printStackTrace(); } }}public class ThreadA extends Thread{ private SyncTest st; public ThreadA(SyncTest syncTest){ this.st=syncTest; } public void run(){ st.methodA(); }}public class SyncTest { private volatile int i; public static void main(String[] args) throws Exception { new SyncTest().startUp(); } public void startUp(){ for (int a = 0; a < 10; a++) { new ThreadA(this).start(); } } private SomeObj obj = new SomeObj(); public void methodA() { synchronized (obj) { obj.print(i);System.out.println(Thread.currentThread().getName()+DateHelper.getNow() + " god is a girl"); i++; } }}=============================================== synchronized (obj) { 运行结果显示,同步代码块并没有被锁住,而把这行代码的obj替换成this或者随便其他的instance对象,都能锁住代码块。求解? 问题补充:public void print(int i){ //obj替換成this的時候,這行代碼前加syncronized
解决方案
因为wait(1000)会将当前对象obj的控制权(即锁)交出去1秒可以用Thread.sleep(1000)