Implementing a thread requires implementing the Runnable interface, or inheriting the thread class and implementing the Run () method. Define the tasks in the run () method that you want the thread to complete.
Public classLiftOffImplementsRunnable {protected intCountdown = 10; Private Static intTaskcount = 0; Private Final intid = taskcount++; PublicLiftOff () {} PublicLIFTOFF (intcount) { This. Countdown =count; } PublicString State () {return"#" +id+ "(" + (Countdown>0?countdown: "LiftOff") + ")."; } @Override Public voidrun () {//TODO auto-generated Method Stub while(countdown--> 0) {System.out.print (State ()); Thread.yield (); } System.out.println ("Liftoff already!!"); }}
Some of the operations and characteristics of the thread:
- Return a value from the thread, you can implement the callable interface, and override the call method.
- Thread hibernation TimeUnit.MILLISECONDS.sleep (), Timeunit is an enumeration class
- Thread can set priority
- Thread Concession yield ()
- Background thread daemon, the background thread will be killed when the non-background thread ends
Thread Pool Interface
To simplify multithreaded programming Java SE5 provides an executor class to manage thread objects for us, and the executor class defines a executor interface at the bottom and declares an Execute method.
Executorservice
is a real thread pool interface that declares some basic methods of thread pooling, submits a task to the thread pool and returns a future object; The Shutdown method no longer accepts new tasks after performing the previously submitted task; Shutdownnow method You try to stop all the tasks that are being performed, stop waiting for the task to execute, and return to the list of pending tasks. Executorservice also has a way to declare the bulk execution of a task, which is not described in detail.
Threadpoolexecutor
is a true thread pool implementation. It implements the executor execute method, the difference between the Execute method and the Submit method is that execute does not have a return value. As a thread pool, the functions that should be provided are the number of threads that set up the thread pool, the containers that hold the waiting threads, and how the redundant tasks are handled, as seen in the Threadpoolexecutor constructor.
Public Threadpoolexecutor (int corepoolsize, int maximumpoolsize, Long KeepAliveTime, timeunit unit, blockingqueue<Runnable> workQueue, Threadfactory threadfactory, rejectedexecutionhandler handler)
The number of threads maintained in the corepoolsize thread pool, even if the thread is idle.
Maximumpoolsize the maximum number of threads in a thread pool
KeepAliveTime a thread that exceeds corepoolsize, and maintains the idle state time waiting for a new task before the end
Unit time unit seconds, MILLISECONDS, microseconds ...
Workqueue is used to hold tasks that are waiting to be executed, and it is important to note that the queue only maintains the tasks that execute commits
Threadfactory Executor Create a new thread to use the factory
Handler to handle tasks that exceed the thread pool capacity
- A task is submitted to the thread pool, and when the number of threads in the thread pool is less than corepoolsize, a new thread is created immediately to handle the task, without the presence of idle threads in the pipeline pool, or when the number of threads is greater than corepoolsize and less than maximumpoolsize. A new thread is created only if the workqueue is full when the workqueue is viewed.
- You can use Prestartcorethread or prestartallcorethreads () to create idle threads to wait for task execution.
- Threads are created by Threadfactory, and by default there are executors threadfactory that create threads with the same thread group, priority, and non-background.
- The
- task Queue Workqueue is available in three types, directly commits ( direct handoffs ), unbounded queues ( unbounded queues ), bounded queues ( bounded queues ).
- commits directly, and the default option for the work queue is synchronousqueue, which submits the task directly to the thread without maintaining it. Here, if there is no thread available to run the task immediately, attempting to join the task to the queue will fail, and a new thread will be constructed. This policy avoids locking when processing a set of requests that may have internal dependencies. Direct submissions typically require unbounded maximumpoolsizes to avoid rejecting newly submitted tasks. This policy allows the possibility of an increase in the number of lines that are allowed to continue when the command arrives in a row that exceeds the average that the queue can handle. In a nutshell, this way
- unbounded queues, using unbounded queues (for example, linkedblockingqueue that do not have a predefined capacity) will cause all corepoolsize threads to be busy while the newer tasks are waiting in the queue. This way, the created thread will not exceed corepoolsize. (therefore, the value of maximumpoolsize is not valid) when each task is completely independent of other tasks, that is, when task execution does not affect each other, the use of unbounded queues is appropriate, for example, in a Web page server. This queueing can be used to handle transient burst requests, which allow the possibility of an increase in the number of lines that are allowed to occur when the command reaches an average of more than the queue can handle.
- bounded queues, when using limited maximumpoolsizes, a bounded queue (such as arrayblockingqueue) helps prevent resource exhaustion, but can be difficult to adjust and control. The queue size and maximum pool size may need to be compromised: using large queues and small pools minimizes CPU usage, operating system resources, and context switching overhead, but can result in artificially reduced throughput. If tasks are frequently blocked (for example, if they are I/O boundaries), the system may schedule more threads than you permit. Using small queues typically requires a large pool size, high CPU utilization, but may encounter unacceptable scheduling overhead, which also reduces throughput.
- Task reject Rejectedexecutionhandler is used to handle executor shutdown, limited queue, and limited maximumpoolsize capacity beyond the issue. Threadpoolexecutor defines four types of Rejectedexecutionhandler
- Threadpoolexecutor.abortpolicy throwing run-time rejectedexecutionexception exception
- The Threadpoolexecutor.callerrunspolicy thread invokes the execute itself that runs the task. This strategy provides a simple feedback control mechanism that can slow down the submission of new tasks.
- Threadpoolexecutor.discardpolicy tasks that cannot be performed will be discarded.
- Threadpoolexecutor.discardoldestpolicy If the execution program has not been closed, the task at the head of the work queue is deleted, and then the execution of the program is retried (repeat this process if it fails again)
- The hook function, which provides BeforeExecute (Thread, Runnable), AfterExecute (Runnable, Throwable) interfaces, is called before and after a task is executed.
Scheduledexecutorservice
is a executorservice that provides the ability to schedule tasks for a given delay or periodicity.
PublicScheduledfuture<?>Schedule (Runnable command,Longdelay, timeunit unit); Public<V> scheduledfuture<v> Schedule (callable<v>Callable,Longdelay, timeunit unit); PublicScheduledfuture<?>scheduleatfixedrate (Runnable command,LongInitialDelay,Longperiod, timeunit unit); PublicScheduledfuture<?>schedulewithfixeddelay (Runnable command,LongInitialDelay,Longdelay, timeunit unit);
The first two functions execute the task after delaying delay, and the scheduleatfixedrate repeats the task after waiting for time delay and period the schedulewithfixeddelay after waiting for the initial delay initialdelay. and waits for the delay to repeat the task after each execution of the task.
Executors
Executors mainly provides a number of factory methods that are used to generate commonly used thread pools:
- public static Executorservice Newcachedthreadpool (), using Synchronousqueue to save the task waiting to run, maximumpoolsize to the maximum value of integer.
- public static Executorservice Newfixedthreadpool (), the size of the thread pool corepoolsize and maximumpoolsize are the same size, Using unbounded queue linkedblockingqueue.
- public static Executorservice Newsinglethreadexecutor (), fixedthreadpool with a size of 1, using unbounded queues Linkedblockingqueue
- public static Scheduledexecutorservice Newscheduledthreadpool, creating a thread pool that can specify deferred execution or a specified execution period
Public Static voidCachedpool () {Executorservice exec=Executors.newcachedthreadpool (); for(inti = 0; I < 5; ++i) {exec.submit (NewLiftOff ()); } exec.shutdown ();} Public Static voidFixedpool () {Executorservice exec= Executors.newfixedthreadpool (3); for(inti = 0; I < 5; ++i) {exec.submit (NewLiftOff ()); } exec.shutdown ();} Public Static voidSinglethread () {Executorservice exec=Executors.newsinglethreadexecutor (); for(inti = 0; I < 5; ++i) {exec.submit (NewLiftOff ()); } exec.shutdown ();} Public Static voidScheduledthread () {scheduledthreadpoolexecutor exec= (Scheduledthreadpoolexecutor) Executors.newscheduledthreadpool (2); Exec.scheduleatfixedrate (NewLiftOff (), 3, 12, Timeunit.seconds); Exec.scheduleatfixedrate (NewLiftOff (), 3, 6, timeunit.seconds);}
Reference: http://blog.csdn.net/sd0902/article/details/8395677, JDK 1.7 API
Java multithreaded thread pool