The content of this article is about how to create multi-threading in Java? (Details), it has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
What is a thread:
A thread is an entity in the process. It is a basic unit that is independently scheduled and dispatched by the system. The thread itself does not own system resources, only It is an indispensable resource during operation, but it can share all the resources owned by the process with other threads belonging to the same process.
On the surface, it is multi-threading, but it is actually a fast execution of the CPU in turns.
##Multi-threading (parallel and concurrency)- Parallel: two tasks are performed at the same time, that is, while task A is executing, task B is also executing (multi-core required)
- Concurrency: Both tasks are requested to run, and the processor can only accept one task, so the two tasks are scheduled to be executed in turn. Since the time interval is very short, it makes people feel that both tasks are running
public class TestThread { public static void main(String[] args) { //4.创建Thread的子类对象 MyThread myThread = new MyThread(); //5.启动线程,注意这里使用的是start而不是run方法 myThread.start(); for (int i = 0; i < 10000; i ++) { System.out.println("This is main thread"); } } } //1.继承Thread class MyThread extends Thread{ //2.重写run方法 @Override public void run() { super.run(); //3.线程方法中要执行的代码,可以根据自己的需求填写 for(int i = 0 ; i < 10000 ; i ++ ) { System.out.println("This is MyThread thread "); } } }How to create multi-threads in java(1) Inherit the Thread class and call the start method Thread implements the Runnable interface
To implement multi-threading, you must become a subclass of thread and override the run method. Note that when starting a thread, it is not the run method but the start method that is called. If the run method is called, it is equivalent to a normal method and does not open the thread
public class Thread implements Runnable
public class TestThread { public static void main(String[] args) { MyThread myThread = new MyThread(); //注意这里使用的是start而不是run方法 myThread.start(); for (int i = 0; i < 10000; i ++) { System.out.println("This is main thread"); } } } class MyThread extends Thread{ @Override public void run() { super.run(); for(int i = 0 ; i < 10000 ; i ++ ) { System.out.println("This is MyThread thread "); } } }(2) Implement the runnable interface and rewrite the run methodThere is only one method in Runnable, run(), The thread startup method exists in Thread,
then when we finally start the thread, we must start the thread through the subclass object of Thread
public class TestRunnable { public static void main(String[] args) { //4.创建Thread的子类对象 Runnable myRunnable = new MyRunnable(); //5.启动线程,创建Thread并把runnable的子类作为构造参数 new Thread(myRunnable).start(); for (int i = 0; i < 10000; i ++) { System.out.println("This is main thread"); } } } //1.实现runnable接口 class MyRunnable implements Runnable { //2.重写run方法 @Override public void run() { //3.线程方法中要执行的代码,可以根据自己的需求填写 for(int i = 0 ; i < 10000 ; i ++ ) { System.out.println("This is MyRunnable thread "); } } }implement the Callable interface To implement threads, in addition to inheriting thread and runnable, you can also implement the Callable interface. The Callable interface provides a call() method that can be used as a thread execution body, which has the same function as run(). But the call() method has more return values than the run() method, and the call() method can declare the exception thrown. So how do we start the Callable thread? Because the Callable interface is not a sub-interface of the Runnable interface, the Callable object cannot be used as a construction parameter of Thread. Java provides another interface, the RunnableFuture interface, which implements Runnable, Future
- implementation
Callableinterface
- Write the
call method, which is equivalent to the run method in thread. The difference is that the call method allows a return value
- Pass the Callable implementation class object as a construction parameter to FutureTask to create a FutureTask object.
- Pass the FutureTask object as a construction parameter to Thread and start the thread
public class CallableDemo { public static void main(String[] args) { //3.把Callable实现类对象作为构造参数传入FutureTask创建FutureTask对象。 FutureTask<UUID> futureTask = new FutureTask<UUID>(new MyCallable()); //4.把FutureTask对象作为构造参数传入Thread,并开启线程 new Thread(futureTask).start(); try { System.out.println(futureTask.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } //1. 实现**Callable**接口 class MyCallable implements Callable<UUID> { //2.重写**call**方法,相当于thread中的run方法。不同的是call方法允许有返回值 @Override public UUID call() throws Exception { //生成随机数 return UUID.randomUUID(); } }
From the source code implementationInherit ThreadThe subclass rewrites the run() method in Thread and calls the start() method. The jvm will automatically call the subclass's run() Implementing Runnablenew Thread(myRunnable) puts the reference of runnable in the constructor of Thread, and then passes it to the member variable target of thread. In the Thread run() method, it is determined that if the target is not empty, the run method of the subclass is called
public void run() { if (this.target != null) { this.target.run(); }Implements the Callable interfaceImplements the Callable interface and overrides the Call() method, and can Provides thread return values and can also throw exceptions. Finally, it is passed to the member variable target of Thread through the implementation class FutureTask of Runnable's sub-interface RunnableFuture. In terms of use and expansionInherit Thread
- Advantages: Directly call the start() method in thread, very simple
- Disadvantages: Java only supports single inheritance. If a subclass inherits thread, it cannot inherit other classes
- Advantages: java can implement many things
- Disadvantages: The code writing is complicated and start() cannot be called directly
- Advantages: Java can be implemented in multiple ways, can throw exceptions, and can have return values
- Disadvantages: Code writing is complicated
The above is the detailed content of How to create multithreading in java? (detailed). For more information, please follow other related articles on the PHP Chinese website!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version