我觉得在使用synchronized代码块或函数中,只有一个锁的情况下,使用this锁就是最好的。- <span style="font-size:12px;">public class InputOutputDemo2
- {
- public static void main(String[] args)
- {
- Res1 r=new Res1();
- Thread t1=new Thread(new Input1(r));
- Thread t2=new Thread(new Output1(r));
- t1.start();
- t2.start();
-
- }
- }
- class Res1
- {
- private String name;
- private String sex;
- private boolean flag=false;
- public synchronized void set(String name,String sex)//set和out是同步的,只需要设置一个锁,那么用this就可以了。
- {
- if(flag)
- try{this.wait();}catch(InterruptedException e){}
- this.name=name;
- this.sex=sex;
- flag=true;
- this.notify();
- }
- public synchronized void out()
- {
- if(!flag)
- try{this.wait();}catch(InterruptedException e){}
- System.out.println(name+"-----"+sex);
- flag=false;
- this.notify();
- }
- }
- class Input1 implements Runnable
- {
- private Res1 r;
- Input1(Res1 r)
- {
- this.r=r;
- }
- public void run()
- {
- int x=0;
- while(true)
- {
- if(x==0)
- r.set("zhangsan","man");
- else
- r.set("lisi","woman");
- x=(x+1)%2;
- }
- }
- }
- class Output1 implements Runnable
- {
- private Res1 r;
- Output1(Res1 r)
- {
- this.r=r;
- }
- public void run()
- {
- while(true)
- {
- r.out();
- }
- }
- }
- </span>
复制代码 但是有两个以上的锁时,我们就需要另外建立对象,将其做为锁了。- public class DeadThreadDemo {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Thread t1=new Thread(new Test(true));
- Thread t2=new Thread(new Test(false));
- t1.start();
- t2.start();
- }
- }
- class Test implements Runnable
- {
- private boolean flag;
- Test(boolean flag)
- {
- this.flag=flag;
- }
- public void run()
- {
- if (flag)
- {
- while (true)
- {
- synchronized(MyLock.locka)// 1 1与2两个代码块不是同步的,我们就需要建立两个对象,成为两个不同的锁。
- {
- System.out.println("if locka");
- synchronized(MyLock.lockb)
- {
- System.out.println("if lockb");
- }
- }
- }
- }
- else
- {
- while(true)
- {
- synchronized(MyLock.lockb)// 2
- {
- System.out.println("else lockb");
- synchronized(MyLock.locka)
- {
- System.out.println("else locka");
- }
- }
- }
- }
- }
- }
- class MyLock
- {
- static Object locka=new Object();
- static Object lockb=new Object();
- }
复制代码 在线程间通讯的情况下,使用Lock更为方便更有针对性。 |