Three ways to implement multi-threading in java
In Java, there are three ways to implement multi-threading. The first method: inherit the Thread class and override the run function. The second method: implement the Runnable interface and rewrite the run function. The third method: implement the Callable interface and override the call function. This article will explain how these three methods can be implemented through examples. If you need it, please refer to it.
(1) Inherit the Thread class and override the run function.
class xx extends Thread{ public void run(){ Thread.sleep(1000) //The thread sleeps for 1000 milliseconds, sleep causes the thread to enter the Block state and release resources}} Start thread:
Object.start() //Start the thread, run the run function
(2) Implement the Runnable interface, the code is as follows
class MyThread implements Runnable { private String name; public MyThread(String name) { super(); this.name = name; } @Override public void run() { for(int i = 0 ; i < 200; i++) { System.out.println("Thread"+name+"--->"+i); } }}public class ThreadDemo { public static void main(String[] args) { MyThread a = new MyThread("a"); MyThread b = new MyThread("b"); MyThread c = new MyThread("c"); new Thread(a).start(); new Thread(b).start(); new Thread(c).start(); }}(3) Implement the Callable interface and override the call function
Callable is an interface similar to Runnable. The classes that implement the Callable interface and the classes that implement the Runnable are tasks that can be executed by other threads.
There are several differences between Callable and Runnable:
Java Callable code example:
class TaskWithResult implements Callable<String> { private int id; public TaskWithResult(int id) { this.id = id; } @Override public String call() throws Exception { return "result of TaskWithResult " + id; }}public class CallableTest { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService exec = Executors.newCachedThreadPool(); ArrayList<Future<String>> results = new ArrayList<Future<String>>(); //Future is equivalent to a container used to store the results of Executor execution for (int i = 0; i < 10; i++) { results.add(exec.submit(new TaskWithResult(i))); } for (Future<String> fs : results) { if (fs.isDone()) { System.out.println(fs.get()); } else { System.out.println("Future result is not yet complete"); } } exec.shutdown(); }}Thank you for reading, I hope it can help you. Thank you for your support for this site!