java中线程的同步性

/*
 *目的:测试同步代码块和同步函数锁定同一个对象才能实现线程安全
 *其实我们能够实现线程同步其实就是因为我们在运行到某一个线程的时候,设置了一个标志
 *也就是我们锁定了一个对象,要实现线程的同步,我们每次锁定的对象必须要是同一个
 */
class Lesson5TestDemo1
{

 public static void main(String [] args)
 {
  Lesson5TestDemo2 rr = new Lesson5TestDemo2();
  //调用start函数只是让这个线程处于就绪状态,并不是已经马上就去运行这个线程,可能还运行在其他的线程上,只不过让这个线程处于就绪状态了
  new Thread(rr).start();
  //这是让其他的线程停下,让这个就绪状态的线程运行起来
  try{Thread.sleep(1);}catch(Exception e){}
  rr.str = new String("method");
      new Thread(rr).start();
  //new Thread(rr).start();
  //new Thread(rr).start();
 }
}


class Lesson5TestDemo2 implements Runnable
{
 private int tickets = 100;
 String str = new String("");
 public void run()
 {
  if(str.equals(""))
  {
   //这里锁定的str,由于同步代码块和同步函数锁定不是同一个对象,所以还是会出错
   //要是我们的同步代码块和我们的同步函数锁定 同一个对象,那么就不会出错了
   //synchronized(str)
   synchronized(this)
   {
    while(true)
    {
     if(tickets > 0)
     {
      try{Thread.sleep(10);}catch(Exception e){}
      System.out.println("nosale");
      System.out.println(Thread.currentThread().getName() + " is saling ticket of " + tickets--);
     }
    }
   }
  }
  else
  {
   //其实这里锁定的是this
   sale();
  }
 }
 public synchronized void sale()
 {
  while(true)
  {
   if(tickets > 0)
   {
    try{Thread.sleep(10);}catch(Exception e){}
    System.out.println("sale");
    System.out.println(Thread.currentThread().getName() + " is saling ticket of " + tickets--);
   }
  }
 }
 
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值