public class PingPong implements Runnable {
synchronized void hit(long n) {
for (int i = 1; i < 3; i++)
System.out.print(n + "-" + i + " ");
}
public static void main(String[] args) {
new Thread(new PingPong()).start();
new Thread(new PingPong()).start();
}
public void run() {
hit(Thread.currentThread().getId());
}
}
上面的代码给出了输出8-1 9-1 8-2 9-2。
但是,由于函数是同步的,它应该给出输出8-1 8-2 9-1 9-2或9-1 9-2 8-1 8-2。
有人能解释一下吗?
发布于 2011-09-07 18:25:56
方法上的“同步”同步特定对象上该方法的所有访问。
因此,如果您有一个PingPong
对象,那么没有2个线程会同时输入它的hit
方法,但是对于2个对象,一个线程可以输入其中一个对象的hit
方法,而另一个线程运行另一个对象的hit
对象。
这是有意义的,因为您通常使用synchronized
来确保对当前对象本地内容的不受干扰的访问。如果您的对象表示线程有时需要不受干扰的访问的某个外部实体,则使您的对象成为单例。
发布于 2011-09-07 18:30:09
要获得您想要的行为,请尝试进行以下更改:
public class PingPong implements Runnable {
synchronized void hit(long n) {
for (int i = 1; i < 3; i++)
System.out.print(n + "-" + i + " ");
}
public static void main(String[] args) {
PingPong p = new PingPong();
new Thread(p).start();
new Thread(p).start();
}
public void run() {
hit(Thread.currentThread().getId());
}
}
只有一个PingPong
实例,hit()
上的synchronized
修饰符将防止一个线程中断另一个线程,您的输出要么是X-1 X-2 Y-1 Y-2
,要么是visa-相反。
发布于 2011-09-07 18:26:25
根据http://download.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html
首先,不可能对同一对象上的同步方法进行两次调用来交织。
因此,由于您有两个PingPong对象,所以同步关键字不像您预期的那样工作。
https://stackoverflow.com/questions/7338661
复制相似问题