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?