synchronized

rotApple 2011-03-28 05:59:52
public synchronized void abc()
{
array.push("123");
}

public void abc()
{
synchronized(array)
{
array.push("123");
}
}

二者性能相同吗?
...全文
129 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
rotApple 2011-03-29
  • 打赏
  • 举报
回复
另一个:

public static void main(String args[])
{
Thread t = new Thread(new Runnable(){

private final Object threadBlo = new Object();

public void run()
{
try
{
synchronized(threadBlo)
{
System.out.println("start to wait...");
threadBlo.wait();
}
}
catch(InterruptedException e)
{
System.out.println("interrupted!");
}
}
});

t.start();

try{
Thread.sleep(3000);}catch(InterruptedException e){}
t.interrupt();
}


为什么t.interrupted会让threadBlo抛出interruptedexception?
rotApple 2011-03-29
  • 打赏
  • 举报
回复
5楼。

也就是说实际上第一种是加在了this上?
那么如果有def方法的话。 一个线程在访问abc时,其它线程无法访问def?
  • 打赏
  • 举报
回复
使用对象监视器都不同,没有可比性!

如果第二个用的是 synchronized(this) 的话,那么是一样的效果。
php17 2011-03-28
  • 打赏
  • 举报
回复
在多个线程的时候是不一样啊。。
php17 2011-03-28
  • 打赏
  • 举报
回复
不同啊。。
sxabu 2011-03-28
  • 打赏
  • 举报
回复
如果存在多个线程则不同,不加synchronized有可能造成数据损坏或脏数据

51,411

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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