您的位置:首页 > 其它

关于synchronized

2012-09-12 14:01 141 查看
今天在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;
}

@Override
public 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;
}

@Override
public 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的理解又更深了一步。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  class thread string