关于synchronized(this)同步无效的疑问

ggjjzhzz 2005-01-20 05:39:24
创建两个线程和一个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)但总是失败。谁有比较好的例子让我参考一下。
...全文
490 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
ggjjzhzz 2005-01-20
  • 打赏
  • 举报
回复
谢谢两位,但我还是没搞懂:我锁的不是方法,而是Inner对象啊。

记得有学习资料上说:synchronized(this),即对象锁,当一个线程访问这个语句块时,其它线程对这个this对象的任何访问都会被阻塞。不知对不对?
whyxx 2005-01-20
  • 打赏
  • 举报
回复
m2也加上同步就行了.
iforem 2005-01-20
  • 打赏
  • 举报
回复

在线程t1调用m1()的整个过程中,t2对m2()的访问应该被拒绝.
-----------------------------

m2()不是一个同步方法啊
t2可以访问m2,当t1调用m1()的时候

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧