博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Fibonacci
阅读量:4667 次
发布时间:2019-06-09

本文共 2827 字,大约阅读时间需要 9 分钟。

1 //Copyright (C) Microsoft Corporation.  All rights reserved.  2  3 using System;  4 using System.Threading;  5  6 // The Fibonacci class provides an interface for using an auxiliary  7 // thread to perform the lengthy Fibonacci(N) calculation.  8 // N is provided to the Fibonacci constructor, along with an  9 // event that the object signals when the operation is complete. 10 // The result can then be retrieved with the FibOfN property. 11 public class Fibonacci 12 {
13 public Fibonacci(int n, ManualResetEvent doneEvent) 14 {
15 _n = n; 16 _doneEvent = doneEvent; 17 } 18 19 // Wrapper method for use with thread pool. 20 public void ThreadPoolCallback(Object threadContext) 21 {
22 int threadIndex = (int)threadContext; 23 Console.WriteLine("thread {0} started...", threadIndex); 24 _fibOfN = Calculate(_n); 25 Console.WriteLine("thread {0} result calculated...", threadIndex); 26 _doneEvent.Set(); 27 } 28 29 // Recursive method that calculates the Nth Fibonacci number. 30 public int Calculate(int n) 31 {
32 if (n <= 1) 33 {
34 return n; 35 } 36 else 37 {
38 return Calculate(n - 1) + Calculate(n - 2); 39 } 40 } 41 42 public int N { get { return _n; } } 43 private int _n; 44 45 public int FibOfN { get { return _fibOfN; } } 46 private int _fibOfN; 47 48 ManualResetEvent _doneEvent; 49 } 50 51 public class ThreadPoolExample 52 {
53 static void Main44() 54 {
55 const int FibonacciCalculations = 10; 56 57 // One event is used for each Fibonacci object 58 var doneEvents = new ManualResetEvent[FibonacciCalculations]; 59 var fibArray = new Fibonacci[FibonacciCalculations]; 60 var r = new Random(); 61 62 // Configure and launch threads using ThreadPool: 63 Console.WriteLine("launching {0} tasks...", FibonacciCalculations); 64 for (int i = 0; i < FibonacciCalculations; i++) 65 {
66 doneEvents[i] = new ManualResetEvent(false); 67 var f = new Fibonacci(r.Next(20, 40), doneEvents[i]); 68 fibArray[i] = f; 69 ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i); 70 } 71 72 // Wait for all threads in pool to calculation... 73 WaitHandle.WaitAll(doneEvents); 74 Console.WriteLine("Calculations complete."); 75 76 // Display the results... 77 for (int i = 0; i < FibonacciCalculations; i++) 78 {
79 Fibonacci f = fibArray[i]; 80 Console.WriteLine("Fibonacci({0}) = {1}", f.N, f.FibOfN); 81 } 82 } 83 }

 

转载于:https://www.cnblogs.com/calvin88/archive/2012/03/03/2378763.html

你可能感兴趣的文章
关于Java 8 forEach
查看>>
.NET设计模式(1):1.1 单例模式(Singleton Pattern)
查看>>
创建模态对话框和非模态对话框
查看>>
08-图8 How Long Does It Take
查看>>
二维数组中最大连通子数组
查看>>
java 正则表达式-忽略大小写与多行匹配
查看>>
mac 上亚马逊密钥登录
查看>>
css选择器中:first-child与:first-of-type的区别
查看>>
nopcommerce 二次开发
查看>>
NHibernate入门实例
查看>>
IBM_DS5020磁盘阵列做raid、热备并把盘阵挂在服务器上的步骤
查看>>
svg制作风车旋转
查看>>
《软件工程》课堂作业:返回一个整数数组中最大字数组的和
查看>>
ACM 美素数 (没AC)
查看>>
Sqlserver学习研究
查看>>
VTK图形模型主要对象
查看>>
c# Linq实现 获得某一个路径下所有文件的名(不含扩展名)
查看>>
动静态广播的区别
查看>>
前缀式计算(前缀表达式)
查看>>
Android手机通讯录解析
查看>>