本帖最后由 张凯 于 2012-7-19 20:02 编辑
代码如下:
package com;
public class method {
private static method m = null;
private static byte[] b = new byte[0];
private method(){
}
public static method getInstance(){
if(m==null){
m = new method();
}
return m;
}
public void print1(){
synchronized (b) {
for(int i = 0;i<1220;i++){
System.out.println(Thread.currentThread().getName()+i);
}
}
}
public void print2(){
synchronized (b) {
for(int i = 0;i<1220;i++){
System.out.println(Thread.currentThread().getName()+i);
}
}
}
}
package com;
public class test {
public static void main(String[] args) {
test t=new test();
t.init();
}
public void init(){
Runnable r = new thread1();
Thread t = new Thread(r,"A");
t.start();
Runnable r1 = new thread2();
Thread t1 = new Thread(r,"B");
t1.start();
}
public class thread1 implements Runnable{
public void run() {
method m = method.getInstance();
m.print1();
}
}
public class thread2 implements Runnable{
public void run() {
method m = method.getInstance();
m.print2();
}
}
}
问题:
如若synchronized (b)中的b是static 则执行的结果是AB按顺序出现,若b是非static则AB交替出现,若b换成thisAB也是交替出现。谁能给我解释下为什么吗,method类中的两个方法里的锁不是指向同一个对象吗。谢谢 。。。。 |