简体   繁体   English

了解同步

[英]Understanding synchronized

Given this code: 鉴于此代码:

public class Messager implements Runnable {            

  public static void main(String[] args) {   
      new Thread(new Messager("Wallace")).start();    
      new Thread(new Messager("Gromit")).start();             
  }             
  private String name;                 
  public Messager(String name) { this.name = name; }             
  public void run() {    
      message(1); message(2);    
  }           
  private synchronized void message(int n) {    
    System.out.print(name + "-" + n + " ");    
  }    
}

I understand that the synchronized keyword makes the thread dependent on the object's lock. 我知道synchronized关键字使线程依赖于对象的锁。 Questions: 问题:

a) Is the lock released as soon as the method marked as synchronized finishes? a)一旦标记为synchronized的方法完成,锁就会被释放吗? Or as soon as the thread's run() method finishes b) Can I ensure that any one of the threads will print its name and 1 2 before the other? 或者一旦线程的run()方法完成,b)我可以确保任何一个线程都打印出它的名字,并且1 2先于另一个线程打印出来吗?

A. Yes. 答:是的。 It's released as soon as the synchronized function finishes. 它在synchronized函数完成后立即释放。
B. Yes. B.是的。 You can, but if you wanted to do so, why would you write multithreaded code in the first place? 你可以,但如果你想这样做,为什么你会首先编写多线程代码? synchronized guarantees atomicity, not anything regarding the order, but you can enforce order by waiting for a flag to change. synchronized保证原子性,而不是有关订单的任何内容,但您可以通过等待标志更改来强制执行订单。 Anyway, what you are trying to enforce is sequentiality . 无论如何,你想要强制执行的是顺序性 You get this for free in single-threaded environments :) 你可以在单线程环境中免费获得这个:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM