了解同步

发布于 2024-08-15 06:03:24 字数 749 浏览 10 评论 0原文

给出这段代码:

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 + " ");    
  }    
}

我知道 synchronized 关键字使线程依赖于对象的锁。问题:

a) 标记为 synchronized 的方法完成后,锁是否会立即释放?或者一旦线程的 run() 方法完成 b) 我能否确保任何一个线程都会在另一个线程之前打印其名称和 1 2

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. Questions:

a) Is the lock released as soon as the method marked as synchronized finishes? 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只是在用心讲痛 2024-08-22 06:03:24

答:是的。 synchronized 函数完成后就会立即释放。
B、是的。可以,但如果您想这样做,为什么首先要编写多线程代码呢? synchronized 保证原子性,而不是与顺序有关的任何内容,但您可以通过等待标志更改来强制执行顺序。不管怎样,你想要强制执行的是顺序性。您可以在单线程环境中免费获得它:)

A. Yes. It's released as soon as the synchronized function finishes.
B. Yes. 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. Anyway, what you are trying to enforce is sequentiality. You get this for free in single-threaded environments :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文