【问题标题】:Thread.sleep() with synchronization in javaThread.sleep() 与 java 中的同步
【发布时间】:2010-12-18 18:35:28
【问题描述】:

当调用 Thread.sleep(10000) 时,当前线程将进入睡眠状态。 如果在同步方法中调用了 Thread.sleep(10000) 其他线程是否可以在这段时间内执行?

【问题讨论】:

    标签: java multithreading synchronized


    【解决方案1】:

    如果您在同步方法中执行Thread.sleep(10000) 或阻止您不要释放锁定。因此,如果其他线程正在等待该锁,它们将无法执行。

    如果您想等待指定的时间量让条件发生并释放您需要使用的对象锁Object.wait(long)

    【讨论】:

      【解决方案2】:
      private synchronized void deduct()
      {
          System.out.println(Thread.currentThread().getName()+ " Before Deduction "+balance);
          if(Thread.currentThread().getName().equals("First") && balance>=50)
          {
              System.out.println(Thread.currentThread().getName()+ " Have Sufficent balance will sleep now "+balance);
              try
              {
                  Thread.currentThread().sleep(100);
              }
              catch(Exception e)
              {
                  System.out.println("ThreadInterrupted");
              }
              balance =  balance - 50;
          }
          else if(Thread.currentThread().getName().equals("Second") && balance>=100)
          {
              balance = balance - 100;
          }
              System.out.println(Thread.currentThread().getName()+ " After Deduction "+balance);
          System.out.println(Thread.currentThread().getName()+ " "+balance);
      }
      

      我将此方法设为同步,我运行了两个同时运行的单独线程并执行此方法产生了不需要的结果!! 如果我评论 try catch 块它会运行良好,那么同步块的使用是否受到限制,直到 m 不使用这些 try catch 块

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-27
        • 2010-10-08
        相关资源
        最近更新 更多