关于synchronized(this)同步无效的疑问
创建两个线程和一个Inner对象,t1访问Inner对象的m1()方法;t2访问Inner对象的m2()方法。
package ths;
public class Thread16 {
private class Inner {
private void m1() {
synchronized(this) { //同步块!
System.out.println("\n[" + this + "] m1() start");
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
}
System.out.println("\n[" + this + "] m1() end");
}
}
private void m2() {
Thread th = Thread.currentThread();
String name = th.getName();
int i = 10;
System.out.println("\n[" + this + "] m2() start");
while (i-- > 0) {
System.out.print(name + ".");
try {
Thread.sleep(50);
} catch (InterruptedException ie) {
}
}
System.out.println("\n[" + this + "] m2() end");
}
}
public static void main(String[] args) {
Thread16 t16 = new Thread16();
final Inner i = t16.new Inner();
Thread t1 = new Thread(
new Runnable() {
public void run() {
i.m1();
}
},"1"
);
Thread t2 = new Thread(
new Runnable() {
public void run() {
i.m2();
}
}, "2"
);
t1.start();
t2.start();
}
}
结果:
K:\test12>javac -d .\cls .\src\Thread16.java
K:\test12>java -classpath .\cls ths.Thread16
[ths.Thread16$Inner@9cab16] m2() start
2.
[ths.Thread16$Inner@9cab16] m1() start
2.2.2.2.2.2.2.2.2.
[ths.Thread16$Inner@9cab16] m2() end
[ths.Thread16$Inner@9cab16] m1() end
K:\test12>
按我对synchronized(this)的理解,在线程t1调用m1()的整个过程中,t2对m2()的访问应该被拒绝。但现在这两个方法却是同时访问的。请大家看看问题出在哪里?
编了几个程序来测试synchronized(this)但总是失败。谁有比较好的例子让我参考一下。