当前位置: 技术问答>java相关
连接池问题!不能取得唯一的实例!救命,搞了一个早上了~
来源: 互联网 发布时间:2015-06-01
本文导语: public class MedicareApplication { static private MedicareApplication mApp; static synchronized public MedicareApplication getInstance() { if (mApp == null) { mApp = new MedicareApplication(); } return...
public class MedicareApplication {
static private MedicareApplication mApp;
static synchronized public MedicareApplication getInstance() {
if (mApp == null) {
mApp = new MedicareApplication();
}
return mApp;
}
...
}
我的类1中写了 MedicareApplication.getInstance();取得了实例。
而在类2中写MedicareApplication ma = MedicareApplication.getInstance(),想获得之前在类1中生成的实例,赋予给ma 。
但是不行!!!! 跟踪getInstance() 里的mApp,每次都是null。
static private MedicareApplication mApp;
static synchronized public MedicareApplication getInstance() {
if (mApp == null) {
mApp = new MedicareApplication();
}
return mApp;
}
...
}
我的类1中写了 MedicareApplication.getInstance();取得了实例。
而在类2中写MedicareApplication ma = MedicareApplication.getInstance(),想获得之前在类1中生成的实例,赋予给ma 。
但是不行!!!! 跟踪getInstance() 里的mApp,每次都是null。
|
先把你的程序简化点.一步一步试.
我试了一下,是可以的.
public class MedicareApplication {
static private MedicareApplication mApp;
static synchronized public MedicareApplication getInstance() {
if (mApp == null) {
mApp = new MedicareApplication();
}
return mApp;
}
}
public class Test {
public Test() {
}
public void test1() {
MedicareApplication ma = MedicareApplication.getInstance();
System.out.println(ma);
}
public void test2() {
MedicareApplication ma = MedicareApplication.getInstance();
System.out.println(ma);
}
public static void main(String[] args) {
Test t = new Test();
t.test1();
t.test2();
//是同一个对象的地址
}
}
我试了一下,是可以的.
public class MedicareApplication {
static private MedicareApplication mApp;
static synchronized public MedicareApplication getInstance() {
if (mApp == null) {
mApp = new MedicareApplication();
}
return mApp;
}
}
public class Test {
public Test() {
}
public void test1() {
MedicareApplication ma = MedicareApplication.getInstance();
System.out.println(ma);
}
public void test2() {
MedicareApplication ma = MedicareApplication.getInstance();
System.out.println(ma);
}
public static void main(String[] args) {
Test t = new Test();
t.test1();
t.test2();
//是同一个对象的地址
}
}
|
我看着没错呀?
等高手来指点你吧
等高手来指点你吧