最近学习刚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