关于synchronized
来源:互联网 发布:杨振宁 院士 知乎 编辑:程序博客网 时间:2024/06/10 02:00
今天在CSDN看到有人问关于synchronized的帖子,随手写了一个回帖了,然后发现了问题,记录一下。
原帖:http://topic.csdn.net/u/20120912/10/3898dec6-cc46-4587-92ed-0be1a40ebb08.html
在我第一次回答的里面:代码如下(稍微修改了一下):我想说的都在代码的注释里。
public class SynDemo{public static void main(String[] args){Test test = new Test();new T1(test).start();new T1(test).start();}}class T1 extends Thread{private Test test;T1(Test test){this.test = test;}@Overridepublic void run(){//在这里循环调用test,每次调用完就释放掉了Test的锁,所以下一个test方法是能进去的,所以就达不到预期效果。for(int i = 0; i < 10; i ++){try{Thread.sleep((long)(Math.random() * 500));}catch (InterruptedException e){e.printStackTrace();}test.test();}}}class Test{synchronized public void test(){System.out.println(Thread.currentThread().getName() + " hello");}}第二次回答的代码:
public class Syn{public static void main(String[] args){D d = new D();new MyThread(d).start();new MyThread(d).start();}}class MyThread extends Thread{private D d;public MyThread(D d){this.d = d;}@Overridepublic void run(){d.test();}}class D{synchronized public void test(){//在这里循环,每次循环完并不释放掉锁,所以能达到预期的效果。for(int i = 0 ; i < 10; i ++){try{Thread.sleep((long)(Math.random() * 500));}catch (InterruptedException e){e.printStackTrace();}System.out.println(Thread.currentThread().getName() + " hello");}}}
总结一下,由于不细心,导致错误,不过自己对synchronized的理解又更深了一步。
- 关于synchronized
- 关于synchronized
- 关于synchronized
- 关于synchronized
- 关于synchronized
- 关于synchronized
- 关于synchronized
- 关于synchronized
- 关于synchronized
- 关于synchronized
- 关于 @synchronized
- 关于synchronized
- 关于volatile和synchronized
- 关于synchronized(this)
- 关于 synchronized 的使用
- 关于volatile和synchronized
- 关于synchronized(this)
- 关于synchronized(obj)
- 嫣然一笑苦了情
- 模块问题
- C++设计模式----抽象工厂
- Android通过共享用户ID来实现多个Activity进程共享
- 原子性和可视性
- 关于synchronized
- Android中View绘制流程以及invalidate()等相关方法分析
- android定位和地图开发实例
- 在校女大二学生,借助阿里巴巴年收入十万
- android知识点
- buffer cache —— latch: cache buffers lru chain
- python apache2 Internal Server Error
- 启用auto trace功能
- SQL中 patindex函数的用法