首页 新闻 会员 周边

.net线程ManualResetEvent用法疑问

0
悬赏园豆:50 [待解决问题]

在学习线程,遇到个问题,不太清楚.希望各位园友一起讨论解答!一起成长谢谢!

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadDemoConsole
{
    class BankManualResetEvent
    {
        private double account1 = 2500;
        private double account2 = 1000;
        public ManualResetEvent mre = new ManualResetEvent(false);

        public void Transfering()
        {
            mre.Reset();//设置对象mre处于无信号状态
            Console.WriteLine("转账前账户account1还剩余的金额:" + account1.ToString());

            Console.Write("转账金额(元):");
            double sum = double.Parse(Console.ReadLine());
            if (sum > account1)
            {
                Console.WriteLine("转账金额超出了账户account1所剩的金额,转账失败!");
                return;
            }

            account1 = account1 - sum;
            account2 = account2 + sum;
            Console.WriteLine("转账后账户account1还剩余的金额:" + account1.ToString());
            mre.Set();//设置对象mre处于有信号状态
        }

        public void Fetching()
        {
            //阻止当前线程(线程user2)的运行,知道收到对象mre发的信息
            mre.WaitOne();
            Thread.Sleep(100);
            account1 = account1 - 2000;
        }
    }

    class ManualResetEventThread
    {
        static void Main(string[] args)
        {
            BankManualResetEvent a = new BankManualResetEvent();
            Thread user1 = new Thread(new ThreadStart(a.Transfering));
            Thread user2 = new Thread(new ThreadStart(a.Fetching));
            user1.Start();
            user2.Start();
            Console.ReadKey();
        }
    }
}

结果有时是2500,有疑惑

lsjhello的主页 lsjhello | 初学一级 | 园豆:149
提问于:2015-07-12 11:41
< >
分享
所有回答(1)
0

建议你去http://www.foundexception.com/提问,很多高手回答

刘珍宝 | 园豆:289 (菜鸟二级) | 2015-07-12 11:55

终于明白了Console.ReadKey();不能要.

解释是不是应该这样,希望大家指教:

我创建了2个线程,那么当前程序还应该有一个主线程。

Console.ReadKey();在主线程中.而线程执行是无序的,

那么double sum = double.Parse(Console.ReadLine());就也有肯那个读取到Console.ReadKey()的值

效果是这样的:

支持(0) 反对(0) lsjhello | 园豆:149 (初学一级) | 2015-07-12 15:03
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册