java multi-thread thread pool
First of all, the pool is a design pattern, which means that a lot of the cost is higher than the connection of these in order to provide performance, with a pool to do the cache. For example, a string pool, such as a database connection pool, here introduces the thread pool.
The cost of starting a thread in a system is still high, because it involves interacting with the operating system. The specific design ideas and database connection pool are similar:
The thread pool creates a large number of idle threads at system startup, and the program passes a Runnable object to the thread pool, which initiates a thread to execute the Run method of the object, and when the Run method executes, it does not die and returns to the pool again to become idle. The Run method that waits for the next Runnable object to execute.
Java built-in supports thread pooling after JDK1.5. The following are the steps to perform thread tasks using the thread pool:
1, call the static factory method of the executors class to create a Executorservice object that represents a thread pool.
2, create the Runnable implementation class, and of course you can create the callable implementation class as a thread to perform tasks
3, call the Executorservice object's Submit method to submit the above runnable instance
4, when you do not want to invoke the shutdown method of the Executorservice object when committing any tasks to close the thread pool
The specific code is as follows:
Import java.util.concurrent.*;//implements the Runnable interface to define a simple threading class Linkinthread implements Runnable{public void Run () {for ( int i = 0; I < 100; i++) {//After using the pool, the name of the thread becomes "pool-1-thread-1" such as the System.out.println (Thread.CurrentThread (). GetName () + "" + i);}} public class Threadpooltest{public static void Main (string[] args) throws exception{// Create a thread pool with a fixed number of threads (6) Executorservice pool = Executors.newfixedthreadpool (6);//Submit two thread pool.submit to the thread pool (new Linkinthread ());p Ool.submit (New Linkinthread ());//close thread pool Pool.shutdown ();}}
Java multi-thread thread pool