Java中synchronized,sleep()和wait()的初略认知

最近学习刚Java中锁的概念(是看着传智的视频看的)

先来说说synchronized吧,一开始没有认真思考,一直以为synchronized是把整个区域锁了起来,后来才知道原来它的作用是把一个对象锁了起来,也就是说即使他修饰的是整段代码,当对象改变的时候,程序依旧可以访问那段代码。如果依旧要使用synchronized,那么操作的时候一定要操作同一个对象,这样synchronized才可以起作用,

class Resource 
{
private String name;
private int num = 0;
private boolean flag = false;
public synchronized void set(String name)
{
while(flag)
try{this.wait();}catch(Exception e){}
this.name = name + num++;
System.out.println(Thread.currentThread().getName()+"...Producer..."+this.name);
flag = true;
notify();



}
public synchronized void show()
{
while(!flag)
try{this.wait();}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"...Consumer........."+this.name);
flag = false;
notify();
}
}
class Produce implements Runnable
{
Resource re;
Produce(Resource re)
{
this.re = re;
}
public void run()
{
while(true)
{
re.set("+Ping+");
}
}
}
class Consumer implements Runnable
{
Resource re;
Consumer(Resource re)
{
this.re = re;
}
public void run()
{
while(true)
{
re.show();
}
}
}
class ShowProDuce
{
public static void main(String[] args)
{
Resource r = new Resource();
Produce pr = new Produce(r);
Consumer con = new Consumer(r);

Thread t1 = new Thread(pr);
Thread t2 = new Thread(pr);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}

2.关于sleep()和wait()的区别,在博客园(DreamSea(张小哲))看到一篇讲解,觉得够用了http://www.cnblogs.com/DreamSea/archive/2012/01/16/2263844.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值