Two ways: an Inheritance thread class implementation, one by implementing the callable interface.
The first method:
Because the Run method that implements the thread class itself does not have a return value, it is not possible to get the execution result of the thread directly, but you can get the value of the instance variable by passing the final result to the instance variable in the Run method, and then using the Getxx method. Code that inherits the implementation:
[Java]View Plaincopy
- Class Runthread extends thread{
- private String Runlog;
- private BufferedReader BR;
- {
- Runlog = "";
- }
- Public Runthread (BufferedReader br) {
- this.br = BR;
- }
- public Void Run () {
- try {
- String output = "";
- While (output = Br.readline ()) = null) {
- This.runlog + = output + "\ n";
- }
- } catch (IOException e) {
- E.printstacktrace ();
- }
- }
- Public String Getrunlog () {
- return This.runlog;
- }
- }
The second method:
The call method needs to be implemented after inheriting the callable interface, which can have a return value by default, so you can return directly to what you want to return. Implementation code for the interface:
[Java]View Plaincopy
- Class Callthread implements callable<string>{
- private String Runlog;
- private BufferedReader BR;
- {
- Runlog = "";
- }
- Public Callthread (BufferedReader br) {
- this.br = BR;
- }
- @Override
- Public String Call () throws Exception {
- try {
- String output = "";
- While (output = Br.readline ()) = null) {
- Runlog + = output + "\ n";
- }
- } catch (IOException e) {
- return runlog;
- }
- return runlog;
- }
- }
The following is called.
The first way of calling code:
[Java]View Plaincopy
- Runthread Th1 = new Runthread (standout);
- Th1.start ();
- Runthread Th2 = new Runthread (STANDERR);
- Th2.start ();
- Th2.join (); //Ensure that the previous 2 threads end before the main process, otherwise the obtained result may be empty or incomplete
- Runlog + = Th1.getrunlog () + "\ n";
- Runlog + = Th2.getrunlog () + "\ n";
The second way of calling code:
[Java]View Plaincopy
- Executorservice Exs = Executors.newcachedthreadpool ();
- Arraylist<future<string>> al = new arraylist<future<string>> ();
- Al.add (Exs.submit (new Callthread (standout)));
- Al.add (Exs.submit (new Callthread (Standerr)));
- For (future<string> fs:al) {
- try {
- Runlog + = Fs.get () + "\ n";
- } catch (Interruptedexception e) {
- E.printstacktrace ();
- } catch (Executionexception e) {
- E.printstacktrace ();
- }
- }
Java Multithreading returns function results