Use J2SE1.5 to create a multi-task Java application 2

Source: Internet
Author: User

Future and FutureTask

In earlier versions of Java, it is very difficult to query the running thread status and return a value after the thread is executed. Because the run (run) method returns void, you must write a lot of code to return a value from the thread. Programmers who have used this method must understand their painful experiences.

You can use the Future interface or the FutureTask class to obtain a return value from the asynchronous thread. The Future interface provides some methods to check whether the computing process is complete, retrieve the computing results, or terminate the computing process. The FutureTask class provides the basic implementation of the Future interface method (implementation ). Results can be retrieved only after the computing process is completed. If the calculation process is not completed, the get method will be blocked ).

The MyStringReverser. java file in the downloaded code demonstrates the use of the FutureTask class and provides an easy-to-understand example. It displays the submitted string from the back to the front at a speed of one character per second, and the main thread checks whether the transaction is completed:

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 is completed, use the get method to retrieve the result from the Future object:

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

ThreadPoolExecutor (thread pool executor)

With the ThreadPoolExecutor class, you can write your own server. This class provides many features for configuring and adjusting servers, similar to many large-scale enterprise-level EJB servers. Below are some of its configuration parameters:

· Core and maximum thread pool size

By setting corePoolSize and maximumPoolSize to the same value, you can create a fixed thread pool. By setting maximumPoolSize to a large value (such as Integer. MAX_VALUE), you can allow the thread pool to accommodate any number of concurrent transactions.

· Construct as needed

By default, ThreadPoolExecutor starts to establish and start the Core Thread only when new transactions are required. However, you can use prestartCoreThread or prestartAllCoreThreads to dynamically reload it.

· Maintain the activity time

If the number of threads in the thread pool exceeds the corePoolSize, these threads will be terminated when their idle time exceeds keepAliveTime.

· Queuing

Queuing follows the following rules:

· If the number of running threads is less than corePoolSize, Executor will always add new threads instead of waiting in line.

· If corePoolSize or more threads are running, Executor queues requests without adding new threads.

· If a request cannot participate in the queue, a new thread will be created unless the number of threads exceeds maximumPoolSize (when the number of threads exceeds, the transaction will be rejected ).

· Hook method

This class provides beforeExecute () and afterExecute () hook methods, which are called before and after each transaction is executed. To use them, you must create a subclass of this class (because these methods are protected ).

In the downloaded code, MyThreadPoolExecutor. java provides detailed examples of monitoring multiple configuration parameters. You can find that the thread pool and queue size are changing as each transaction increases and completes. You can modify the settings in the code. Concurrent set

JDK 1.5 provides the following set implementations, which are designed for multithreading environments:

· ConcurrentHashMap

· CopyOnWriteArrayList

· CopyOnWriteArraySet

The ConcurrentHashMap class provides complete thread-safe concurrency support for the expected concurrency that can be adjusted for retrieval and update. CopyOnWriteArraySet is a set of thread-safe variables. CopyOnArrayList is a thread-safe array list variable. Before modifying the original array or set, each of them copies the lower-layer array or set. The result is that the read speed is very fast, and the update speed is very slow.

The concurrent collection class provides snapshot-type data for Iterator (iterative sub-) (even if the underlying data changes, it is not reflected in Iterator ).

Synchronizer)

JDK 1.5 also provides some advanced classes, such as Semaphore, CountDownLatch, and CyclicBarrier, as well as an Exchanger (switch) class for synchronization. This article does not describe the detailed analysis and usage information of these classes, because understanding them requires some theoretical background.

With these new classes, you can persuade technical superiors who are afraid of multithreading technology to develop multi-threaded applications.

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.