我想創建一個控制檯應用程序,它將爲四個函數創建四個線程,然後獲取函數將返回的內容。線程1必須計算一個用隨機數填充的數組的總和並返回它,線程2計算同一數組的產品並將其返回,線程3創建並返回一個-1000,1000之間的隨機整數,第四個取和,產品和x(隨機數),比較它們並顯示誰比誰更大。C#:設置線程和獲取函數返回值
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace threadsproject
{
class Program
{
public int thread1(int [] a, int n)
{
int i = n;
int sum = 0;
for (int j = 0; j < i; j++)
{
sum = a[j] + sum;
}
Console.WriteLine("\nThe sum is: ");
return sum;
}
public int thread2(int[] a, int n)
{
int prod = 1;
for (int j = 0; j < n; j++)
{
prod = a[j] * prod;
}
Console.WriteLine("\nThe product is: ");
return prod;
}
public int thread3()
{
Random rnd = new Random();
int x;
x = rnd.Next(-1000, 1000);
Console.WriteLine("\nYour random number is: {0}", x);
return x;
}
public void thread4(int sum, int prod, int x)
{
Console.WriteLine("\n");
if (sum < prod && prod < x)
{
Console.WriteLine("T1,T2,T3");
}
else if (sum < x && x < prod)
{
Console.WriteLine("T1,T3,T2");
}
else if (x < sum && sum < prod)
{
Console.WriteLine("T2,T1,T3");
}
else if (x < prod && prod < sum)
{
Console.WriteLine("T2,T3,T1");
}
else if (prod < sum && sum < x)
{
Console.WriteLine("T3,T1,T2");
}
else if(prod < sum && sum == x)
{
Console.WriteLine("T3,T1=T2");
}
if (sum < prod && prod == x)
{
Console.WriteLine("T1,T2==T3");
}
else
Console.WriteLine("T3,T2,T1");
}
static void Main(string[] args)
{
Random rnd = new Random();
string s;
int n;
int [] numbers = null;
Console.WriteLine("Give the size of the array: ");
s = Console.ReadLine();
n = int.Parse(s);
for(int i=0; i<n; i++)
{
numbers[i] = rnd.Next(-100, 100);
}
int sum, prod, x;
Thread mythread1 = new Thread(delegate() { thread1(numbers, n); });
Thread mythread2 = new Thread(delegate() { thread2(numbers, n); });
Thread mythread3 = new Thread(() => thread3());
Thread mythread4 = new Thread(delegate() { thread4(sum, prod, x); });
mythread1.Start();
mythread2.Start();
mythread3.Start();
mythread4.Start();
}
}
}
所以,當我創建的線程,我得到了同樣的錯誤給所有的對象引用需要非靜態字段,方法或屬性「threadsproject.Program.thread < 1,2,4>(int int int)'。我在Visual Studio 2013 .net 4.6上工作。在線程上沒有很好的編程經驗,我想幫助理解我做錯了什麼。在此先感謝大家!
總是一個好主意,谷歌的錯誤信息。 –