Ok, so can some one explain to me the gap in my knowledge here?
Initially the example below was trying to synchronize an instance method, but then realised that I spawn a new instance and therefore a lock wouldn’t happen.
So I decided to make a lock on a static method of the class in the hope that the thread would then run in order but still no luck. Can any explain the error of my ways? ( Bear with me there are probably better ways to do this its just getting the understanding right, I’m a PHP developer going into Java, I love it – but I’m only 2 days in 😉 )
So at this time the numbers print out in a random order.
Class 1
package learningjava;
public class LearningJava {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ThreadCaller ob1 = new ThreadCaller("This is a test string 1");
ThreadCaller ob2 = new ThreadCaller("This is a test string 2");
ThreadCaller ob3 = new ThreadCaller("This is a test string 3");
ThreadCaller ob4 = new ThreadCaller("This is a test string 4");
ThreadCaller ob5 = new ThreadCaller("This is a test string 5");
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
ob4.t.join();
ob5.t.join();
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
Class 2
package learningjava;
public class ThreadCaller implements Runnable {
private String message;
public Thread t;
public ThreadCaller(String text) {
message = text;
t = new Thread(this);
t.start();
}
public static synchronized void echo(String message) {
System.out.println(message);
}
public void run() {
ThreadCaller.echo(this.message);
}
}
Basically, you’re expecting ordering which simply isn’t guaranteed. You’re calling
start()on lots of threads in succession… there’s no guarantee about which one will actually start executing first. The fact that you’ve got a static synchronized method just means that only one thread will be executing that method at a time – it doesn’t guarantee anything about ordering.Imagine you have a running track with a one-lane gate 100m down the track. You start the race – which runner will reach the gate first?
Fortunately, this isn’t usually a problem – if it’s worth starting multiple threads to do something, you usually don’t care about the order in which they execute. If you do, it’s time to re-examine your design.