下面是源代码:
public class Counter
{
private int num = 0 ;
static private Counter counter = null;
private Counter() {
Console.WriteLine("the class Counter has been instaned!");
} static public Counter getInstance()
{
if (counter!= null)
return new Counter();
else return counter;
} public int count() {
return num++;
}
}就是一个计数器,然后让不同的线程调用它,调用代码如下:
public static void ThreadProc()
{
for (int i = 0; i < 10; i++) {
Console.WriteLine("ThreadProc: {0}", Counter.getInstance().count());
// Yield the rest of the time slice.
Thread.Sleep(0);
}
}可是报的错误是System.NullReferenceException: 未将对象引用设置到对象的实例
麻烦哪位大虾帮忙解决一下
public class Counter
{
private int num = 0 ;
static private Counter counter = null;
private Counter() {
Console.WriteLine("the class Counter has been instaned!");
} static public Counter getInstance()
{
if (counter!= null)
return new Counter();
else return counter;
} public int count() {
return num++;
}
}就是一个计数器,然后让不同的线程调用它,调用代码如下:
public static void ThreadProc()
{
for (int i = 0; i < 10; i++) {
Console.WriteLine("ThreadProc: {0}", Counter.getInstance().count());
// Yield the rest of the time slice.
Thread.Sleep(0);
}
}可是报的错误是System.NullReferenceException: 未将对象引用设置到对象的实例
麻烦哪位大虾帮忙解决一下
解决方案 »
- 课件整合器,遇到个难题,跪求高手指点
- 在线等,急求winform中的日历控件如何获取选择的日期
- 关于vs2008的增量编译问题
- 关于调用方法,VS2008中不能自动弹出调用函数,求救ing...
- OracleHelper的类型初始值设定项引发异常
- 梅花鱼控件在哪可以下载 谢了!!!
- listview增加一行时闪烁怎么解决啊?还有就是增选一行滚动条自动往下滚怎么做?
- 能不能Stream对象把邮件附件输出到客户端进行下载啊,急!!
- 急!!急!!急!!急!!急!!根据自定义的schema生成相应的xml文件
- listview的有关操作?
- formLoad事件之后不停的刷新显示的数据,碰到的问题
- sql 怎么访问accsess数据库
或静态类
但现在又出现新问题了,就是不同的线程启动之后,输出的值都是0,好像num根本没有增加,这是怎么回事啊!
the class Counter has been instaned!
ThreadProc: 0
the class Counter has been instaned!
ThreadProc: 0
the class Counter has been instaned!
ThreadProc: 0
the class Counter has been instaned!
ThreadProc: 0
the class Counter has been instaned!
ThreadProc: 0
the class Counter has been instaned!
ThreadProc: 0
the class Counter has been instaned!
ThreadProc: 0
这个方法写错了,应该是这样
static public Counter getInstance()
{
if (counter == null)
counter = new Counter(); return counter;
}
谢谢楼上的两位
http://hd.qu365.com/?P382933