Obtain operation results from Java threads

Source: Internet
Author: User
Java threads are implemented by threads. Generally, we create a thread to perform a complex operation and then process the operation results in the main thread. However, the thread's run function does not return values, so how can we notify other threads After calculating the result? This article describes several methods to return information.
I. Java thread Creation
 
There are two ways to create a thread. One is to inherit the Thread class, the other is to implement runnable, and then pass it to a thread constructor, the example is as follows (Suppose we want to calculate the sum of 1 to 10000 in a thread ):
1. Inherit thread:
Public class addthread extends thread {
Public void run (){
Int result = 0;
For (INT I = 1; I <= 10000; I ++ ){
Result + = I;
}
}
}
Run addthread:
Addthread thread = new addthread ();
Thread. Start ();
2. Implementation interface runnable:
Public class add implements runnable {
Public void run (){
Int result = 0;
For (INT I = 1; I <= 10000; I ++ ){
Result + = I;
}
}
}
Run this thread: thread = new thread (new add ());
Thread. Start ();
Ii. Method for Returning Calculation Results
 
Now, after starting this addition thread, we need to get the operation result from this thread. For example, we want to display the operation result in the main thread. So how can we implement it? The following describes several common methods. Note that some of them are incorrect methods.
1. Use the get method (incorrect)
We can add a getresult function to addthread to obtain the calculation result:
Public class addthread extends thread {
Private int result = 0;
Public void run (){
For (INT I = 0; I <= 10000; I ++)
Result + = I;
}
Public int getresult (){
Return result;
}
}
 
/** Obtain the calculation result and display it on the screen.
*/
Public class test {
Public static void main (string [] ARGs ){
Addthread thread = new addthread ();
Thread. Start ();
System. Out. println ("result is" + thread. getresult ());
}
}
 
The result is: result is 0.
 
Because the main thread and the addthread thread run at the same time, and the addthread operation has not been completed (or even not started), the main thread starts to output the calculation result, so this method is wrong.
 
2. Query Method (feasible but inefficient)

The second method is to use the hasdone variable to indicate whether the operation is completed. If hasdone is false, the operation is not completed. Otherwise, the operation is completed. The main thread constantly queries this variable. if it finds that the operation is not completed, it enters the loop wait; otherwise, the calculation result is output.
Public class addthread extends thread {
Private int result = 0;
Private Boolean hasdone = false;
Public void run (){
For (INT I = 0; I <= 10000; I ++)
Result + = I;
Hasdone = true;
}

Public Boolean hasdone (){
Return hasdone;
}

Public int getresult (){
Return result;
}
}
 
Public class test {
Public static void main (string [] ARGs ){
Addthread thread = new addthread ();
Thread. Start ();
File: // if the operation is not completed, wait cyclically
While (! Thread. hasdone ()){
Try {
Thread. Sleep (100 );
}
Catch (interruptedexception ex ){
}
}
If (thread. hasdone ())
System. Out. println ("result is" + thread. getresult ());

}

}
The result is 50005000.


The status of the cyclic query operation in the main thread. If the operation is not completed, the main thread sleep100 milliseconds and continues the query. This method is feasible, but because the main thread performs cyclic query, it consumes a lot of CPU time, so the efficiency is very low.

3. Wait/notify mode (better)
The third method is in the form of wait/notify. When the calculation is not completed, the main thread enters the sleep state, so it does not occupy the CPU, so the efficiency is high.
 
Public class addthread
Extends thread {
File: // wait on this object
Private object lock;
Private int result = 0;
Private Boolean hasdone = false;

Public addthread (Object lock ){
This. Lock = lock;
}

Public void run (){
For (INT I = 0; I <= 10000; I ++)
Result + = I;
File: // The operation ends, notifying the waiting thread
Synchronized (LOCK ){
Hasdone = true;
Lock. policyall ();
}
}

Public Boolean hasdone (){
Return hasdone;
}

Public int getresult (){
Return result;
}
}
 
File: // main thread
Public class test {
Public static void main (string [] ARGs ){
Object lock = new object ();
Addthread thread = new addthread (Lock );
Thread. Start ();
Synchronized (LOCK ){
While (! Thread. hasdone ()){
Try {
File: // when the operation is not completed, the main thread enters the sleep state. When addthread executes policyall, it will wake up the main thread.
Lock. Wait ();
}
Catch (interruptedexception ex ){
}
}
}
If (thread. hasdone ())
System. Out. println ("result is" + thread. getresult ());
}
}

4. Use callback (better)
 
I think this is the best method. After the computation is completed, addthread automatically calls the result processing class. The extension can enable multiple listener to process the results. Here the observer mode is used. This method is very simple and does not need to consider the synchronization mechanism. The specific implementation is as follows:
File: // interface for processing results
Public interface resultprocessor {
Public void process (INT result );
}
 
Public class addthread extends thread {
Private resultprocessor processor;

Public addthread (resultprocessor processor ){
This. processor = processor;
}

Public void run (){
Int result = 0;
For (INT I = 0; I <= 10000; I ++ ){
Result + = I;
}
File: // process the result
Processor. Process (result );
}
}
Public class test implements resultprocessor {
Public void process (INT result ){
System. Out. println ("result is" + result );
}

Public static void main (string [] ARGs ){
Test test = new test ();
Addthread thread = new addthread (test );
Thread. Start ();
}
}
The result is 50005000.
 
As shown in the code above, the addthread constructor is passed into a result processing class. when the operation is completed, the processing function of this class is automatically called to process the result. In comparison, I think this method is the best.

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.