synchronized 自己的例子

public class MySync
{
 
 public synchronized void AAA()
 {
   System.out.println("aaa begin");
     try{Thread.sleep(5000);}
     catch(Exception ex){}
  System.out.println("this is method  aaa");
  System.out.println("aaa  end");
  System.out.println("--------------------------------");
 }
 public  void BBB()
 {
  System.out.println("bbb  begin");
    try{Thread.sleep(5000);}
    catch(Exception ex){}
  System.out.println("this is method  bbb");
  System.out.println("bbb  end");
  System.out.println("--------------------------------");
 }
 public synchronized void DDD()
 {
  System.out.println("ddd  begin");
    try{Thread.sleep(5000);}
    catch(Exception ex){}
  System.out.println("this is method  ddd");
  System.out.println("ddd  end");
  System.out.println("--------------------------------");
 }
 public void CCC()
 {
  System.out.println("ccc  begin");
  System.out.println("this is method  ccc");
  System.out.println("ccc  end");
  System.out.println("--------------------------------");
 }
 synchronized static void method(){
        System.out.println("static begin");
        try{Thread.sleep(2000);}
        catch(Exception ex){}
        System.out.println("static end"); 
    }
}

 

 

 

 

 

 

 

 

 

public class Test  extends Thread
{
 private MySync ms = null;
 private String ty = null;
 public MySync getMs()
 {
  return ms;
 }
 public void setMs(MySync ms)
 {
  this.ms = ms;
 }
 public String getTy()
 {
  return ty;
 }
 public void setTy(String ty)
 {
  this.ty = ty;
 }
 
 public void run()
 {
  if(ty.equals("a"))
   ms.AAA();
  else if(ty.equals("b"))
   ms.BBB();
  else if(ty.equals("c"))
   ms.CCC();
  else if(ty.equals("d"))
   ms.DDD();
 }


//为了说明将test类的main方法单独说明
 
 
//此main方法可以演示同一类的同一实例在不同线程中的synchronized 效果是互斥的

public static void main(String [] args)
 {
//同一个对象m1,访问两个函数AAA BBB 如果有synchronized,则他们是互斥访问的,一个线程进入
//AAA的时候,另一个无法进入BBB
 
  MySync m = new MySync();
 
  Test t = new Test();
  t.setMs(m);
  t.setTy("a");//t.setTy("b");
  t.start();
 
  t=new Test();
  t.setMs(m);
  t.setTy("b");//t.setTy("a"); 共四种情况,挨个试试,这里的相对于同一个对象m位于不同的进程中
  t.start();
 
 
 
//同一个对象m1,分别在两个不同的线程t2 t3中的表现:如果方法BBB中,没有synchronized,
//说明这两个线程t2 t3 可以随意访问BBB,但是加上synchronized之后,当一个线程进入之后,
//另一个要等进入的线程出来后才能进入
//说明了:同一个对象m1在不同的线程t2 t3中访问synchronized方法是互斥的
  /*
 MySync m1 = new MySync();
 
  Test t2,t3;
  t2=new Test();
  t3=new Test();
 
  t2.setMs(m1);
  t2.setTy("b");
  t2.start();
 
  t3.setMs(m1);
  t3.setTy("b");
  t3.start();
  */
 
  //综上:1,同一个对象,在两个不同的进程中访问一个synchronized函数时,会互斥
  //2,同一个对象,在两个进程中访问多个synchronized函数时,也会互斥
  //3,不同的对象,synchronized函数不起作用
 }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值