62,614
社区成员
发帖
与我相关
我的任务
分享
public class BackgroundFloobleLoader {
public volatile Flooble theFlooble;
public void initInBackground() {
// do lots of stuff
theFlooble = new Flooble(); // this is the only write to theFlooble
}
}
public class SomeOtherClass {
public void doWork() {
while (true) {
// do some stuff...
// use the Flooble, but only if it is ready
if (floobleLoader.theFlooble != null)
doSomething(floobleLoader.theFlooble);
}
}
}
原文作者说如果 theFlooble 引用不是 volatile 类型,doWork() 中的代码在解除对 theFlooble 的引用时,将会得到一个不完全构造的 Flooble。 这句话我看不懂,什么叫做一个不完全构造的Flooble,这段代码不完整,能帮我改一下让我可以在程序中模拟出异常的状况吗?[/quote]
哦。。。我不纠结了,时机到了自然就懂了[img=https://forum.csdn.net/PointForum/ui/scripts/csdn/Plugin/003/monkey/2.gif] [/img] 虽然没解决,不过就你回答了两次,大部分分给你了public class BackgroundFloobleLoader {
public volatile Flooble theFlooble;
public void initInBackground() {
// do lots of stuff
theFlooble = new Flooble(); // this is the only write to theFlooble
}
}
public class SomeOtherClass {
public void doWork() {
while (true) {
// do some stuff...
// use the Flooble, but only if it is ready
if (floobleLoader.theFlooble != null)
doSomething(floobleLoader.theFlooble);
}
}
}
原文作者说如果 theFlooble 引用不是 volatile 类型,doWork() 中的代码在解除对 theFlooble 的引用时,将会得到一个不完全构造的 Flooble。 这句话我看不懂,什么叫做一个不完全构造的Flooble,这段代码不完整,能帮我改一下让我可以在程序中模拟出异常的状况吗?[/quote]
没完整的代码不是很清楚,但是猜测意思是说两个SomeOtherClass的线程,一个线程还在初始化Flooble,另一个线程提前引用了Flooble,第二个线程就把flooble当作了null。这样就会初始化两次,就会有错误。public class BackgroundFloobleLoader {
public volatile Flooble theFlooble;
public void initInBackground() {
// do lots of stuff
theFlooble = new Flooble(); // this is the only write to theFlooble
}
}
public class SomeOtherClass {
public void doWork() {
while (true) {
// do some stuff...
// use the Flooble, but only if it is ready
if (floobleLoader.theFlooble != null)
doSomething(floobleLoader.theFlooble);
}
}
}
原文作者说如果 theFlooble 引用不是 volatile 类型,doWork() 中的代码在解除对 theFlooble 的引用时,将会得到一个不完全构造的 Flooble。 这句话我看不懂,什么叫做一个不完全构造的Flooble,这段代码不完整,能帮我改一下让我可以在程序中模拟出异常的状况吗?[/quote]
我曾经也想模拟出书中提到的各种异常,但是没有几个能复现的。。。public class BackgroundFloobleLoader {
public volatile Flooble theFlooble;
public void initInBackground() {
// do lots of stuff
theFlooble = new Flooble(); // this is the only write to theFlooble
}
}
public class SomeOtherClass {
public void doWork() {
while (true) {
// do some stuff...
// use the Flooble, but only if it is ready
if (floobleLoader.theFlooble != null)
doSomething(floobleLoader.theFlooble);
}
}
}
原文作者说如果 theFlooble 引用不是 volatile 类型,doWork() 中的代码在解除对 theFlooble 的引用时,将会得到一个不完全构造的 Flooble。 这句话我看不懂,什么叫做一个不完全构造的Flooble,这段代码不完整,能帮我改一下让我可以在程序中模拟出异常的状况吗?