Original Address: Http://blog.laofu.online/2017/06/26/producters-consumers/scene
There is a scenario where the program has a very time-consuming operation, but requires a time-consuming operation to perform a time-consuming operation in sequence, and the invocation of the program may be in the same situation.
The specific model is as Follows:
Starting from start, 5 threads are triggered and executed at the same time by a longtimejob, we do not care about Longjob execution time and sequencing, and execute a shortjob according to the order of Start. Below we use code to simulate the process Above.
For example: there are ABCD 4 threads, the order of entry is also abcd,a time-consuming 3s,b time-consuming 7s,c time-consuming 1s,d time-consuming 3s. so if 4 threads start executing at the same time, the order of completion is cadb, but the order we ask is abcd, which means C waits for AB to finish In order to continue the follow-up Work.
We can use the request Bing search to simulate longtimejob, depending on the incoming sequence to determine how many times the request, the main simulation method is as Follows:
Private Static AsyncTask Test () {varArry =New[] { Ten,9,8,7,6,5,4,3,2,1 }; varListtask =Newlist<task<int>>(); foreach(varIinchArry) { varI1 =i; varTask = Task.run (() =Dojob (i1)); Listtask.add (task); } foreach(varTaskinchListtask) {console.writeline ("output-->:"+awaittask);// } } public Statictask<int> Dojob (intO) {returnTask.run (() ={dolongtimething (o); returno; }); } public Static voidDolongtimething (intI) {console.writeline ("executive-->:"+i); for(intj =0; J < i; J + +) {httpget ("http://cn.bing.com/"); } Console.WriteLine ("Execution Completed-->:"+i); } public Static stringHttpGet (stringUrl) { Try{httpwebrequest Request=(httpwebrequest) webrequest.create (url); Request. Method="GET"; HttpWebResponse Response=(httpwebresponse) Request. GetResponse (); StreamReader Reader=NewStreamReader (response. GetResponseStream (), encoding.utf8); stringContent =Reader. ReadToEnd (); returncontent; } Catch(Exception E) {returne.message; } }
Execution Result:
The above code will probably solve our problem, there is a problem, for the customer call we can not form a list, and the list is thread-safe, so for the above method in the actual business scenario can not be used.
New ideas
We cannot implement an ordered task list, and if a different angle is considered, when a task is formed, and a corresponding hashcode is generated at the same time, a queue is queued to the hashcode, and when execution completes longtimejob, Determines whether the hashcode of the first task of the queue, if yes, executes, and if not, continues to wait for the thread to be Switched. The following ideas are as Follows:
public Staticqueue<string> Queue =Newqueue<string>(); Static voidMain (string[] Args) { varArry =New[] { Ten,9,8,7,6,5,4,3,2,1 }; foreach(varIinchArry) {console.writeline ("Enter Job Order-->:"+i); Test (i); } Console.readkey (); } public Static voidTest (intI) {varTaskId =Guid.NewGuid (). ToString (); Queue.enqueue (taskId); Task.Factory.StartNew (dojob,New Object[] {i, taskId}); } public Static voidDojob (ObjectO) {varOarry = (Object[]) o; varn = (int) oarry[0]; varCurrid = oarry[1]. ToString (); Dolongtimething (n);// while(currid! =Queue.peek ()) {thread.sleep (1);//such as thread switching} Console.WriteLine ("doshortjob output-->:"+ n);// //Request DatabaseQueue.dequeue (); } public Static voidDolongtimething (intI) {console.writeline ("longtimejob execution-->:"+i); for(intj =0; J < i; J + +) {httpget ("http://cn.bing.com/"); } Console.WriteLine ("longtimejob Execution Completed-->:"+i); } public Static stringHttpGet (stringUrl) { Try{httpwebrequest Request=(httpwebrequest) webrequest.create (url); Request. Method="GET"; HttpWebResponse Response=(httpwebresponse) Request. GetResponse (); StreamReader Reader=NewStreamReader (response. GetResponseStream (), encoding.utf8); stringContent =Reader. ReadToEnd (); returncontent; } Catch(Exception E) {returne.message; } }
The results of the operation are as Follows:
Although the execution results look messy, Careful comparison can find that the final doshorttime are executed sequentially.
46th how multithreading is queued for execution