Working from the Java thread (original) If there is any opinions, criticism or praise :), please give me a letter climber_2002@sina.com
The Java thread is implemented by thread, usually we create a thread to make a complex operation, then process the calculation result in the main thread, but the Run function of Thread does not return value, then we operate, how to notify Other threads, this paper tells several ways to return information.
One. Java thread creation
To create a thread, there are two ways. One is to inherit the Thread class, and the other is to implement RunNable, then pass it to a Thread constructor, instance, as follows (assuming we want to calculate 1 to 10,000 in a thread):
1. Inherited Thread: Public Class Addthread Extends Thread {public void Run () {int result = 0; for (INT i = 1; i <= 10000; i ) {results = i;}}}
Run addthread: addthread thread = new addthread (); thread.start ();
2. Implement the interface Runnable:
Public class addresss runnable {public void run () {int result = 0; for (int i = 1; i <= 10000; i ) {result = i;}}}
Run the thread: thread thread = new thread (new add ()); thread.start ();
Second, the method of returning the calculation result Now we start this addition thread, you need to get the result of the calculation from this thread, for example, we have to display the calculation results in the main thread. So how do we achieve it? Here is a few common methods, pay attention to some of which is wrong.
1. Using a GET method (wrong) we can join a getResult function in Addthread to get the results: 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;}} / ** Get an operation result and display 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 addthread thread run at the same time, The operation of AddThread has not been completed (or even not yet started), the main thread starts the output operation result, so this approach is wrong. 2. The second method is the use of a variable HasDone to indicate whether the operation is completed if the Hasdone is not completed, otherwise the operation has been completed. The main thread constantly queries this variable, if the operation has not been completed, then enter the loop wait, otherwise the output operation 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.com} public int getResult ()} public class test;}} public class test {public static void main (string [] args) {addthread thread = new addthread (); thread.start (); //// If the operation is not completed, the loop waits for while (! Thread.hasdone ()) {TRY {thread.sleep (100);} catch (interruptedException ex) {}}}}}}}}}}}}}}}}}}}} "Result is" thread.getResult ());}} The result is displayed: Result IS 50005000 The state of the loop query operation in the main thread, if the operation is not completed, then the main thread sleep100 milliseconds, then continue to query, this method is feasible, However, due to the main thread cycle query, a large amount of CPU is consumed, so the efficiency is very low. 3. Wait / Notify mode (better) The third method uses Wait / Notify form, when the operation is not over, the main thread enters the sleep state, then it does not take up the CPU, so the efficiency is higher.
public class AddThread extends Thread {// wait private Object lock on the object; 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; // End, notification waiting thread synchronized (lock) {Hasdone = true; Lock.NotifyAll ();}} public boolean Hasdone ()} return hasDone;} public int getResult () {return result;}} // main thread public class Test {public static void main (String [] args) {Object lock = new Object (); AddThread thread = new AddThread (lock) Thread.Start (); synchronized () {while (! Thread.hasdone ()) {Try {// When the operation does not end, the main thread enters the sleep state, when addthread executes NotifyAll, Wake Wake the main thread Lock.Wait ();} Catch (interruptedexception ex) {}} } F (thread.hasdone ()) System.out.println ("Result is" thread.getResult ());
} 4. I think this is the best way using Callback. When the operation is completed, the AddThread automatically calls the result processing class. The extended extension can be processed to make multiple Listener to the results, which is used here. This method is simple. It does not need to consider the synchronization mechanism, and the specific implementation is as follows: // 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;} // Processor.Process (Result) on the results;}}}} public class test uterplements 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 ();}} 结果 结果: Result IS 50005000 code As above, the constructor of the AddThread passes a result processing class. When the operation is completed, the processing function of this class is automatically invoked to process the results. Compared, I think this method is best. Reference: "Java NewWork Programming" Oreilly