了解同步
给出这段代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
答:是的。
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 :)