好的,那么有人可以在这里向我解释我的知识差距吗?
最初下面的示例试图同步一个实例方法,但后来意识到我生成了一个新实例,因此不会发生锁定。
所以我决定对类的静态方法进行锁定,希望线程能够按顺序运行,但仍然没有运气。任何人都可以解释我的方式的错误吗?(请容忍我,可能有更好的方法来做到这一点,它只是让理解正确,我是一名进入 Java 的 PHP 开发人员,我喜欢它 - 但我只有 2 天时间;-))
所以此时数字以随机顺序打印出来。
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);
}
}
}
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);
}
}