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 keyword synchronizedmakes the thread dependent on locking the object. Questions:
a) Is the lock closed as soon as the method marked as synchronizedends? Or, as soon as the thread method run()ends b) Can I guarantee that any of the threads will print its name 1 2before the other?
source
share