Build multi-threaded Java applications

Source: Internet
Author: User
Core Tip: it is very easy to create a thread pool executor and a threadpoolexecutor. You only need to call the customthreadpoolexecutor class constructor and transmit the appropriate configuration parameters. The following code snippet creates a fixed-size thread pool by defining the same value of the number of core threads and the maximum number of threads: Private threadpoolexecut
  Create a thread pool executor

Creating a threadpoolexecutor is simple. You only need to call the customthreadpoolexecutor class constructor and transmit the appropriate configuration parameters. The following code snippet defines the coreThreadTo create a fixed-size thread pool:

  

Private threadpoolexecutor executor;

Public orderprocessormain (){

// Create a thread pool with fixed number of threads

Executor = new customthreadpoolexecutor (thread_pool_size,

Thread_pool_size, 0l, timeunit. milliseconds,

New linkedblockingqueue ());

..

}

0l value ensures that the working thread is not in the running statusInterrupted. The last parameter is to intercept the queue object and control the task before the task is executed. This queue only controls runnable tasks submitted by the execute method.

Alternatively, you can use the java. Uti. Concurrent. executors function class to create a fixed thread pool.

Executorservice = executors. newfixedthreadpool (2 );

The execution of this method restores the threadpoolexecutor object with a fixed core and maximum thread pool.

  Create and submit a task

After creating a threadpoolexecutor, you need to create a task to process the order. You can use the orderprocessorcallable class created in the previous section to create these tasks. The orderprocessorcallable constructor uses a task name and an order queue object to retrieve the ordervo object.

  

// Create callableTask

Orderprocessorcallable callable1 = new orderprocessorcallable (

"Orderprocessor_1", ordervoqueue );

Remember that the call method of the orderprocessorcallable class will not return until the running variable is correct or the Code throws an exception.

The next step is to store a reference for the callable object. This allows you to call the setrunning method to update the value of the running variable and make the call method return calmly. One advantage of this technology is that you can call other methods to obtain object state information, such as the number of orders processed at a certain point in time.

  

// Store reference to callableObjectIn Collection

Callablemap. Put (callable1.getthreadname (), callable1 );

The preceding code is useful because the future object returned by the executorservice. Submit method cannot be used to obtain the callable object reference or call any method of the callable object.

To execute the orderprocessorcallable task, you call the submit method and transmit a task reference. This method returns a type future object for the following purposes:

  Check task status

Obtain a result object returned by the callable. Call () method.

 Cancel task

  

// Submit callable tasks

Future;

Future = executor. Submit (callable1 );

Futurlist. Add (future );

The future object is also stored in another collection to check the task status and retrieve the processing result. If you do not want to explicitly store future objects in a collection, you can use the executorcompletionservice function class. It provides a useful method for retrieving and deleting completed tasks from an internal task queue.

  Keep task progress tracking

To check the number of orders processed by a task, you can use the orderprocessorcallable object stored in the collection for reference. The following code snippet prints the task status every ms until ordervoqueue is cleared:

  

Private void printprocessorstatus () throws interruptedexception {

// PrintProcessorStatus until all orders are processed

While (! Ordervoqueue. isempty ()){

For (Map. Entry E: callablemap

. Entryset ()){

Logger. Log (E. getkey () + "processed order count :"

+ E. getvalue (). getprocessedcount ());

}

  Thread. Sleep (1000 );

}

}

  Disable threadpoolexecutor and tasks

Executorservice. Shutdown () can be used to close the actuator. When you call Shutdown (), the executor starts an ordered shutdown of all previously submitted tasks, and you may not be submitting new tasks. The following code calls the shutdown () method to prevent new tasks from being submitted. After that, it updates the running status of ordercallable to false, which causes the call method to return.

  

 

// Shutdown ()MethodWill mark the thread pool shutdown to true

Executor. Shutdown ();

// Mark order processor callable to return

For (Map. Entry orderprocessor:

Callablemap. entryset ()){

Orderprocessor. getvalue (). setrunning (false );

}

 Force threadpoolexecutor and task to close

You can call the executorservice. shutdownnow () method to force the actuator to close. Similarly, after calling this method, you do not submit a new task. It stops waiting tasks and sendsInterruptedAn attempt is made to stop a running task. Executorservice. shutdownnow () also restores the list of tasks awaiting execution.

List notexecutedtasks = executor. shutdownnow ();

You can call future. Cancel (Boolean mayinterruptifrunning) to cancel a specific task. The value true indicates the interruption of a task that has been executed. If the task does not start, it does not run. You can use future. iscancelled () to check the canceling status of a task. In this case, return to true if the task is canceled before its normal completion.

  Exception Handling and task results

You can use the future. Get () or future. Get (long timeout, timeunit unit) method to retrieve task results. The no-argument method hinders other methods until the task passes normal execution, cancels, or throws an exception. Use this method with caution because it will wait for the completion of a task indefinitely. The future. Get () method with the timeout parameter is more useful, because it allows a method to return at a specific time:

  

For (Future F: futurlist ){

Try {

  IntegerResult = f. Get (1000, timeunit. milliseconds );

Logger. Log (F + "result. Processed orders" + result );

} Catch (interruptedexception e ){

Logger. Error (E. getmessage (), e );

} Catch (executionexception e ){

Logger. Error (E. getcause (). getmessage (), e );

} Catch (timeoutexception e ){

Logger. Error (E. getmessage (), e );

} Catch (cancellationexception e ){

Logger. Error (E. getmessage (), e );

}

// To avoid printing completed tasks, you may want to remove

// The completedTaskFrom futurelist here

}

The future. Get () method throws different exceptions to give an exact cause for each task failure:

Interruptedexception is thrown -- ifThreadIt is interrupted while waiting for the calculation result.

Timeoutexception is thrown -- if a result is not retrieved within a specified period of time.

Cancellationexception is thrown -- if the calculation is canceled.

Executionexception is thrown -- if a task fails to be computed, any exceptions, including running exceptions, are thrown. This ensures that the execution thread will not be terminated due to an exception in the task execution. The side effect of this behavior is that in the application solution where you want to generate a task running exception, you need to retrieve the running exception from executionexception and throw it again.

  Summary

The orderprocessormain class (see listing 3) uses all the content discussed in the previous section. In particular, the main () method performs the following steps:

Create and configure the customthreadpoolexecutor object.

Create and submit the orderprocessorcallable task.

Put the ordervo object into order-blocking queues.

Periodically print the processor status until the order-blocking queue is empty.

Disable the thread pool processor.

Print the task result after the task is completed.

To view the sample application that is running, run orderprocessormain. Main (String[] ARGs) method. For convenience, provide the source code download (SourceCodeDownload) can be used as an Eclipse project input.

Readers who have read this article have also read:
Java interview abstract classes and interface knowledge points
A Brief Introduction to the usage of Four keywords in Java
JDK Java commands
Use Java to write Oracle stored procedures
JDBC database driver types and selection
This article is collected on the Internet. If your rights are violated, please send a letter to us

From: http://ajava.org/course/java/4961.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.