When the main thread opens up multiple sub-threads and requires that these sub-threads perform the main thread after the completion of the execution, the task's wait method can be implemented in C #, whereas in Java there are types of class Countdownlatch, as follows:
Public Static voidMain (string[] args)throwsinterruptedexception {countdownlatch latch=NewCountdownlatch (3); for(inti = 0; I < 3; i++) {Thread T=NewThread () { Public voidrun () {Try{Thread.Sleep (2000);//pause for 2 secondsSystem.out.println ("Thread:" + This. GetId () + "Done"); } Catch(interruptedexception e) {e.printstacktrace (); } latch.countdown (); } }; T.start (); } System.out.println ("Wait for 3 threads to complete"); Latch.await ();//thread hangs, waits for 3 threads to finish executing before executing the following contentSystem.out.println ("3 threads have been completed");}
First, we need to define the total number of threads and implement the Countdownlatch class, each of which executes the countdown method, which is equivalent to reducing the number of bus threads by one. When Latch.await () detects that the number of threads is 0, follow-up related methods are executed.
Class Countdownlatch in Java similar to task.wait () in C #