A Java Virtual machine allows an application to run multiple threads concurrently. In the Java language, the implementation of multithreading generally has the following three ways:
1) Implement the Runnable interface and implement the run () method of the interface
classMyThreadImplementsrunnable{ Public voidrun () {System.out.println ("Thread Body"); } } Public classtest{ Public Static voidMain (string[] args) {MyThread thread=NewMyThread (); Thread T=NewThread (); T.start (); //Start Thread } }
2) inherit the thread class, overriding the Run method
class extends publicvoid run () { System.out.println ("Thread body");} } Public class publicstaticvoid main (string[] args) { new MyThread (); Thread.Start (); }}
3) Implement callable interface, override Call () method
The callable object is actually a functional class in the executor framework, and the callable interface is similar to the Runnable interface, but provides more powerful functionality than runnable, mainly in the following three points:
(1) callable can provide a return value at the end of the task, runnable cannot provide this functionality.
(2) The call () method in callable can throw an exception, and the Runnable run () method cannot throw an exception.
(3) Running callable can get a future object, and the future object represents the result of an asynchronous calculation. It provides a way to check whether the calculation is complete. Because the thread is part of the asynchronous compute model, it is not possible to get the return value of the method from other threads, in which case the future can be used to monitor the invocation of the call () method by the target thread, and when the Get () method of the future is called to get the result, the current thread blocks until call ( ) method to end the return result.
Importjava.util.concurrent.*; Public classcallableandfuture{ Public Static classCallabletestImplementsCallable<string> { PublicString Call ()throwsException {return"Hello World"; } } Public Static voidMain (string[] args) {Executorservice ThreadPool=Executors.newsinglethreadexecutor (); Future<String> future = Threadpool.submit (Newcallabletest); Try{System.out.println ("Waiting thread to finish"); System.out.println (Future.get ()); } Catch(Exception e) {e.printstacktrace (); } }}
Java Multi-Threading Implementation method