关于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的理解又更深了一步。