The Executors tool class is used to create Java thread pools and timers.
Newfixedthreadpool: Creates a thread pool that can reuse fixed threads, running them in a shared, unbounded queue. At any point, most nthreads threads are in the active state of the processing task. If additional tasks are committed while all threads are active, the additional task waits in the queue until there are available threads. If any thread terminates due to a failure during execution prior to shutdown, a new thread will perform subsequent tasks (if necessary) instead of it. A 关闭 thread in the pool will persist until a thread has been explicitly put in place.
Create a fixed-size thread pool to perform 10 tasks:
Instance:
1Executorservice ThreadPool = Executors.newfixedthreadpool (3);2 for(intj = 0; J < 10; J + +) {3 Final intTask =J;4Threadpool.execute (NewRunnable () {5 @Override6 Public voidrun () {7 for(inti = 0; I < 10; i++) {8 Try {9Thread.Sleep (200);Ten}Catch(interruptedexception e) { One //TODO auto-generated Catch block A e.printstacktrace (); - } -System.out.println (Thread.CurrentThread (). GetName () + "is looping of" + i + "task of" +task); the } - - } - }); +}
Newcachedthreadpool creates a thread pool that can create new threads as needed, but reuses them when previously constructed threads are available. For programs that perform many short-term asynchronous tasks, these thread pools can often improve program performance. Calling Execute reuses the previously constructed thread, if the thread is available. If an existing thread is not available, a new thread is created and added to the pool. Terminates and removes from the cache those threads that have not been used for 60 seconds. Therefore, a thread pool that remains idle for a long time does not use any resources. Note that you can use ThreadPoolExecutor the construction method to create a thread pool with similar attributes but with different details (for example, timeout parameters).
Create a 10-thread cache pool to perform 10 tasks
Instance:
1Executorservice ThreadPool =Executors.newcachedthreadpool ();2 for(intj = 0; J < 10; J + +) {3 Final intTask =J;4Threadpool.execute (NewRunnable () {5 @Override6 Public voidrun () {7 for(inti = 0; I < 10; i++) {8 Try {9Thread.Sleep (200);Ten}Catch(interruptedexception e) { One //TODO auto-generated Catch block A e.printstacktrace (); - } -System.out.println (Thread.CurrentThread (). GetName () + "is looping of" + i + "task of" +task); the } - - } - }); +}
Newsinglethreadexecutor creates a Executor that uses a single worker thread to run the thread in a unbounded queue. (Note that if this single thread is terminated because of a failure during the execution of the shutdown, a new thread will replace it for subsequent tasks if needed). Each task is guaranteed to be executed sequentially, and no more than one thread is active at any given time. Unlike other equivalent Newfixedthreadpool (1) , it is guaranteed to use other threads without reconfiguring the executing program returned by this method.
Create a thread to perform 10 tasks (can be used to let a dead line Cheng re-execute, actually start a new thread)
Instance:
1Executorservice ThreadPool =executors.newsinglethreadexecutor ();2 for(intj = 0; J < 10; J + +) {3 Final intTask =J;4Threadpool.execute (NewRunnable () {5 @Override6 Public voidrun () {7 for(inti = 0; I < 10; i++) {8 Try {9Thread.Sleep (200);Ten}Catch(interruptedexception e) { One //TODO auto-generated Catch block A e.printstacktrace (); - } -System.out.println (Thread.CurrentThread (). GetName () + "is looping of" + i + "task of" +task); the } - - } - }); +}
The difference between shutdown and Shutdownnow
Shutdown: Initiates a sequential shutdown, performs a previously submitted task, but does not accept new tasks. If it is already closed, the call has no other effect.
Shutdownnow: An attempt was made to stop all active tasks that were being performed, suspend processing of the awaited task, and return to the list of tasks awaiting execution. There is no guarantee that you will be able to stop the activity that is being processed, but try it out. For example, by Thread.interrupt() canceling a typical implementation, any task that cannot respond to an outage can never be terminated.
Scheduledexecutorservice thread pool timer. The schedule method creates a task with various delays and returns a task object that can be used to cancel or check execution. The scheduleatfixedrate and schedulewithfixeddelay methods Create and perform certain tasks that run regularly before they are canceled.
Schedule creates and executes a one-time operation that is enabled after a given delay.
1Scheduledexecutorservice Scheduledthreadpool = Executors.newscheduledthreadpool (3);2 for(inti = 0; I < 10; i++) {3 Final intTimer = i;*/4 /*Scheduledthreadpool.schedule (New Runnable () {5 @Override6 Public void Run () {7 try {8 Thread.Sleep (a);9 } catch (Interruptedexception e) {Ten //TODO auto-generated catch block One e.printstacktrace (); A } - System.out.println (Thread.CurrentThread (). GetName () + "" +timer); - } the }, 2, timeunit.seconds);
Scheduleatfixedrate creates and executes a recurring action that is first enabled after a given initial delay, with a given period of time, that is, after InitialDelay , and then in initialdelay+ executes after period, then executes after InitialDelay + 2 * period , and so on. If any one execution of the task encounters an exception, subsequent executions are canceled. Otherwise, the task can only be terminated by executing the cancellation or termination method of the program. If any one execution of this task takes longer than its period, subsequent executions will be deferred, but will not be executed at the same time.
1Scheduledthreadpool.scheduleatfixedrate (NewRunnable () {2 3 @Override4 Public voidrun () {5 Try {6Thread.Sleep (20);7}Catch(interruptedexception e) {8 //TODO auto-generated Catch block9 e.printstacktrace ();Ten } One System.out.println (Thread.CurrentThread (). GetName ()); A } -}, 2, 3, timeunit.seconds);
Schedulewithfixeddelay creates and executes a recurring action that is first enabled after a given initial delay, followed by a given delay between each execution termination and the next execution start. If any execution of a task encounters an exception, subsequent executions are canceled. Otherwise, the task can only be terminated by executing the cancellation or termination method of the program.
1Scheduledthreadpool.schedulewithfixeddelay (NewRunnable () {2 3 @Override4 Public voidrun () {5 Try {6Thread.Sleep (20);7}Catch(interruptedexception e) {8 //TODO auto-generated Catch block9 e.printstacktrace ();Ten } One System.out.println (Thread.CurrentThread (). GetName ()); A } -}, 2, 3, timeunit.seconds);
Java Thread Pool Application