Java线程和同步块 [英] Java threads and synchronized blocks

查看:143
本文介绍了Java线程和同步块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在一个线程中执行同步代码块,并且在同步块中调用方法,该方法生成另一个线程来处理需要与第一个方法相同的锁的同步代码块。所以在伪Java代码中:

Suppose I'm executing a synchronized block of code inside some thread and within the synchronized block I call a method that spawns another thread to process a synchronized block of code that requires the same lock as the first method. So in pseudo Java code:

public void someMethod() {
  synchronized(lock_obj) {
    // a whole bunch of stuff...

    // this is the last statement in the block
    (new Thread(someOtherMethod())).start();
  }
    // some more code that doesn't require a lock
}

public void someOtherMethod() {
  // some setup code that doesn't require a lock

  // return the stuff we want to run in another thread
  // that does require a lock
  return new Runnable() {
    @Override
    public void run() {
      synchronized(lock_obj) {
        // some more code
      }
    }
  };
}

我不知道如何理解这段代码。是我写的甚至是合法的?语法上我没有看到任何问题,但我不知道如何通过这样的代码推理。所以当我执行 someOtherMethod()以创建一个 Runnable 的实例return语句运行?它作为第一个同步块的一部分执行吗?假设有一些其他线程也可能需要在 lock_obj 上锁定。

I have no idea how to make sense of that code. Is what I have written even legal? Syntactically I don't see any issues but I'm not sure how to reason through code like that. So when I execute someOtherMethod() in order to create an instance of Runnable in what kind of scope does the code before the return statement run? Does it execute as part of the first synchronized block? Assume there are some other threads working as well that might require the lock on lock_obj.

推荐答案

在创建runnable和线程期间,你仍然持有锁,但是在调用start之后,线程实际拾取之前你就放弃了锁。新线程将必须与其他线程竞争锁。

You are still holding the lock during the creation of runnable and the thread, but after you call start and before the thread actually picks up you are relinquishing the lock. The new thread will have to compete for the lock with other threads.

这篇关于Java线程和同步块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆