zoukankan      html  css  js  c++  java
  • 使用Thread包装类进行多线程操作

    Java中使用接口的方式,实现方法的回调机制。而在.NET里,我们通过代理,能够很轻松的实现方法的回调。

    class Class1
     {

      [STAThread]
      static void Main(string[] args)
      {
       Class1 c = new Class1();
       ThreadWrapper tw = new ThreadWrapper(new Callback(c.PrintResult), 100);
       // 线程开始
       tw.Start();
       Console.ReadLine();
      }
                      
       // 打印结果,用于回调
      public void PrintResult(int result)
      {
       Console.WriteLine("Result:   " + result.ToString());
      }
     }

     // 回调代理
     public delegate void Callback(int n);

     class ThreadWrapper
     {  
      public readonly Thread mThread;

      private Callback callback;

      private int n;

       // 参数1:用于回调的代理
       // 参数2:需要计算的值

      public ThreadWrapper(Callback callback, int arg)
      {
          this.callback = callback;
          ThreadStart myThreadDelegate = new ThreadStart(this.Run);
          this.mThread = new Thread(myThreadDelegate);
          this.n = arg;
      }

     // 线程的对外接口
      public void Start()
      {
          this.mThread.Start();
      }

      // 需要在线程里调用的方法
      public void Run()
      {
          int result = this.Caculate(this.n);
          callback(result);
      }

      private int Caculate(int n)
      {
          return n*100;
      }
     }
  • 相关阅读:
    CF763C Timofey and Remoduling
    CF762E Radio Stations
    CF762D Maximum Path
    CF763B Timofey and Rectangles
    URAL1696 Salary for Robots
    uva10884 Persephone
    LA4273 Post Offices
    SCU3037 Painting the Balls
    poj3375 Network Connection
    Golang zip压缩文件读写操作
  • 原文地址:https://www.cnblogs.com/top5/p/1550891.html
Copyright © 2011-2022 走看看