LERNINGJAVA 2012-05-30 14:36
浏览 202
已采纳

java锁的问题

代码如下:

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类中的两个方法里的锁不是指向同一个对象吗。谢谢

  • 写回答

3条回答 默认 最新

  • 爱上一条鱼 2012-05-30 15:17
    关注

    哦 那我没仔细看。。。

    你在public static method getInstance()这个函数前加synchronized,这样才保证是singleton,只有一个m

    [code="java"]public synchronized static method getInstance()[/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 使用matlab解决含分段变量的优化问题
  • ¥15 matlab基于鲸鱼算法优化vmd
  • ¥20 PCB设计与制作问答
  • ¥20 课堂跑如何下载ppt
  • ¥15 有没有哥看着画下电路
  • ¥15 STM32阿里云平台显示不了传感器采集的数据
  • ¥20 三菱FX系列PLC上位机串口下指令置位M64和M65,这两条指令分别是什么呢?
  • ¥15 有关结冰模拟程序咨询
  • ¥15 ubuntu服务器配置dns域名后无法访问其他域名
  • ¥50 本人复制了一个关于股票指标的代码,但是运行失败,有没有人帮我解决一下