7 ways to create multi-threads in java
1. Inherit the Thread class
1. Code examples
public class Thread01 extends Thread {
// 线程执行的代码在run()方法中,执行完毕后,线程死亡
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "<我是子线程>");
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "子线程执行完毕");
}
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + "我是主线程");
//启动线程调用start()方法而不是run()方法 调用start()后线程变为就绪状态,而不是运行状态,还需等待CPU调度运行
new Thread01().start();
new Thread01().start();
System.out.println("---主线程执行完毕---");
}
}
The running results are as follows:
main我是主线程
---主线程执行完毕---
Thread-0<我是子线程>
Thread-1<我是子线程>
Thread-1子线程执行完毕
Thread-0子线程执行完毕
2. Summary
It can be seen that the main thread does not need to wait for the sub-thread to finish executing before executing the following program. After the main thread finishes executing, the sub-thread is still executing. Therefore, the error reported by the sub-thread will not affect the main thread.
2. Implement the runable interface
1. Code examples
public class Thread02 implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "<我是子线程>");
}
public static void main(String[] args) {
System.out.println("主程序运行");
new Thread(new Thread02()).start();
new Thread(new Thread02()).start();
System.out.println("主程序运行结束---");
}
}
operation result:
主程序运行
主程序运行结束---
Thread-0<我是子线程>
Thread-1<我是子线程>
3. Use anonymous inner classes
public class Thread02 implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "<我是子线程>");
}
public static void main(String[] args) {
System.out.println("主程序运行");
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "<我是子线程>");
}
}).start();
System.out.println("主程序运行结束---");
}
}
operation result:
主程序运行
主程序运行结束---
Thread-0<我是子线程>
4. Use lambda expressions
public class Thread02 implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "<我是子线程>");
}
public static void main(String[] args) {
System.out.println("主程序运行");
new Thread(() -> System.out.println(Thread.currentThread().getName() + "<我是子线程>")).start();
System.out.println("主程序运行结束---");
}
}
operation result:
主程序运行
主程序运行结束---
Thread-0<我是子线程>
5. Create using callable and Future
1 Introduction
Callable and future can now obtain the returned results. The bottom layer is based on LockSupport. The Callable interface has been provided since JDK5, which is an enhanced version of Runable.
2. Code implementation
public class ThreadCallable implements Callable<Integer> {
/**
* 当前线程需要执行的代码,以及返回结果
* @return
* @throws Exception
*/
@Override
public Integer call() throws Exception {
System.out.println("子线程开始执行。。");
try {
Thread.sleep(3000);
} catch (Exception e) {
}
System.out.println(Thread.currentThread().getName()+":返回1");
return 1;
}
}
public class Thread03 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ThreadCallable threadCallable = new ThreadCallable();
FutureTask<Integer> futureTask = new FutureTask<>(threadCallable);
new Thread(futureTask).start();
Integer result = futureTask.get();
System.out.println(Thread.currentThread().getName()+","+result);
}
}
The running results are as follows:
子线程开始执行。。
Thread-0:返回1
main,1
3. Attention
futureTask can return the result of the thread. In fact, when the get() method is called, the underlying LockSupport calls the LockSupport.park() method, causing the main thread to hang up and wait. After the child thread finishes running and returns the result, it is awakened by LockSupport.unpark(). main thread. Before the child thread returns the result, the main thread is blocked and waiting.
6. Create using thread pool such as Executor framework
public class Thread04 {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> System.out.println("我是子线程"));
}
}
7. spring @Async asynchronous annotation
You only need to write the annotation @Async on the called method. The method annotated by @Async is executed asynchronously, which is equivalent to starting a separate thread in the main thread for execution.