Java applications that use j2se1.5 to implement multitasking

Source: Internet
Author: User
Tags final thread

The J2SE 5.0 platform contains a new concurrency tool package. The classes in this package create blocks (blocking) for concurrent classes (concurrent Classe) or for applications used in concurrent designs. The concurrency tool contains some of the following:

High-performance, flexible thread pool

A framework component that performs transactions asynchronously

Collection class host (host) optimized for concurrent access

This article describes the J2SE 5.0 framework component classes and their important features. The download code for this article provides some simple, easy-to-use examples that demonstrate all the new thread framework component classes. You can have a better understanding of these features by running these examples after you read the content of the article.

Executor (Actuator) Framework component

The Executor framework component provides a simple, standard, extensible class that provides useful functionality that, without these features, can be tedious and difficult to implement manually. This framework component standardizes calls, scheduling, and performing operations. It provides support for controlling asynchronous transactions through a set of execution policies.

The executor interface performs a committed transaction that can be run. It provides a way for us to separate transaction submissions from the transaction execution mechanism. Programmers typically use executor instead of explicitly (explicitly) to create threads. The executor interface also provides synchronous and asynchronous execution of transactions.

For synchronous execution, use the following command:

Class MySynExecutor implements Executor{
public void execute(Runnable r) {
r.run();
}
}

对于异步执行,使用下面的命令:

Class MyASynExecutor implements Executor{
public void execute(Runnable r) {
new Thread(r).start();
}
}

Executorservice (Actuator Service) class

The Executorservice class provides a way to manage the termination of one or more asynchronous transactions and to track the execution of transactions. The Myexecutorservice.java file in the code download demonstrates the process of terminating a management transaction. It initializes a thread pool of size three and then adds the threads in turn. When the number of threads reaches the size limit of the thread pool, it calls the shutdown (shutdown) method. After the shutdown () method is invoked, the thread pool no longer accepts the execution of the new transaction. After waiting 10 seconds, the thread pool calls Shutdownnow (). This method will do its best to terminate all running transactions. In the example, the application failed to attempt to terminate the running thread.

Scheduledexecutorservice (Dispatch Actuator Service)

The Scheduledexecutorservice class is my favorite class. It is very convenient for scheduling transactions that are performed periodically, and transactions that are performed periodically are especially useful for cleanup efforts, such as clearing temporary files created by your application, and so on. The Myscheduledexecutorservice.java file in the download code demonstrates the scheduling process by emitting a "beep" every five seconds:

final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture beeperHandle =scheduler.scheduleAtFixedRate(beeper, 1, 5, SECONDS);

Future and Futuretask

In earlier versions of Java, it was difficult to query the state of threads in a run, and to make a thread return a value after execution. Because the Run method returns void, you must write a large number of code to return a value from the thread. Programmers who have used this method must be aware of their painful experiences.

You can use the future interface or the Futuretask class to get a return value from a thread that executes asynchronously. The future interface provides methods for checking whether the calculation process is complete, retrieving the results of a calculation, or terminating the calculation process. The Futuretask class provides a basic implementation of the Future interface Method (Implementation). The results are retrieved only after the calculation process is complete, and the Get method is blocked (block) if the calculation process is not completed.

The Mystringreverser.java file in the download code demonstrates the use of the Futuretask class and provides an easy to understand example. It displays the submitted string at the rate of one character per second, while the main thread detects whether the transaction is complete:

while(!future.isDone()){
System.out.println("Task not yet completed.");
try{
Thread.currentThread().sleep(500);
}catch(InterruptedException ie){
System.out.println("Will check after 1/2 sec.");
}
}

After the transaction completes, the Get method is used to retrieve the result from the future object:

System.out.println ("Here are result ..." +future.get ());

Threadpoolexecutor (thread pool executor)

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.