内部运行方法中的同步块

AKI*_*WEB 4 java multithreading

如果我有类似下面的东西,那么这意味着什么 synchronized block

synchronised (syncObject) {
Run Code Online (Sandbox Code Playgroud)

基本上,它意味着只有一个线程可以在上面的块中,并且一旦一个线程完成执行,第二个线程将进入同步块同步(syncObject).对?任何人都可以用LayMan语言向我解释,这样我可以获得更好的画面吗?

private static final class Task implements Runnable {
{
  private static Object syncObject = new Object();

    public Task(Command command, BlockingQueue<Integer> pool1, BlockingQueue<Integer> pool2) {
    this.command = command;
    this.existPool = pool1;
    this.newPool = pool2;
}

  public void run()
  {
    synchronised (syncObject) {
      if() {
        existId = existPool.take();
        attributeMethod(existId);
        } else if() {
            newId = newPool.take();
            attributeMethod(newId);
        }
    }
  }
}

// So I need to make this method synchronized or not? Currently I have made this synchronized
private synchronized void attributeMethod(int range) {
    // And suppose If I am calling any other method here-

 sampleMethod();
}


// What about this method, I need to make this synchronized as well? or not?
private synchronized void sampleMethod() {


}
Run Code Online (Sandbox Code Playgroud)

Ste*_*n C 10

基本上,它意味着只有一个线程可以在上面的块中,并且一旦一个线程完成执行,第二个线程将进入同步块同步(syncObject).对?

对!

所以我需要使这个方法同步或不同步?

不,你没有.假设该方法仅从方法中的synchronized块中调用run(),该块将已经阻止多个线程同时执行该方法.因此声明方法synchronized是多余的.

但是,我应该指出一些事情:

  • 当您声明实例方法时synchronized,它将同步this; 即在Task物体上.但是您的synchronized块正在同步一个不同的对象...中的对象syncObject.在这种情况下,这无关紧要.但是,如果方法中的synchronizedrun()不存在,您会发现线程正在尝试在不同的对象上进行同步...并且您不会互相排斥.

  • 通过在方法的顶层同步run()... syncObject对执行该任务的所有线程使用单个共享...您实际上是一次运行一个任务.这完全否定了使用线程的任何好处.

  • 优良作法是声明包含私有锁对象(例如syncObject)的变量final.这避免了某些东西可能会覆盖它的可能性......导致同步失败.