Java multithreading implementation
Java Virtual Machine allows applications to run multiple threads concurrently. In java, multithreading is implemented in the following three methods:
1) Implement the Runnable interface and implement the run () method of this interface
Class MyThread implements Runnable {public void run () {System. out. println ("Thread Body") ;}} public class Test {public static void main (String [] args) {MyThread thread = new MyThread (); thread t = new Thread (); t. start (); // start thread }}
2) inherit the Thread class and override the run method.
class MyThread extends Thread{ public void run() { System.out.println("Thread body"); }}public class Test{ public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); }}
3) Implement the Callable interface and rewrite the call () method.
The Callable object actually belongs to the function class in the Executor framework. The Callable interface is similar to the Runnable interface, but it provides more powerful functions than Runnable, mainly manifested in the following three points:
(1) Callable can provide a return value after the task ends. Runnable cannot provide this function.
(2) The call () method in Callable can throw an exception, while the Runnable run () method cannot throw an exception.
(3) Run Callable to get a Future object, which indicates the result of asynchronous calculation. It provides a method to check whether the computation is complete. Because the thread is an asynchronous computing model, it cannot obtain the return value of the method from other threads. In this case, you can use Future to monitor the call () method calls of the target thread, when you call the get () method of Future to obtain the result, the current thread will be blocked until the call () method ends and the result is returned.
import java.util.concurrent.*;public class CallableAndFuture{ public static class CallableTest implements Callable<String> { public String call() throws Exception { return "Hello World"; } }public static void main(String[] args) { ExecutorService threadPool = Executors.newSingleThreadExecutor(); Future<String> future = threadPool.submit(new CallableTest); try{ System.out.println("waiting thread to finish"); System.out.println(future.get()); } catch(Exception e) { e.printStackTrace(); } }}