The Java thread class is also an object class, and its instances all inherit from java.lang.Thread or its subclasses. You can create a thread in java in the following way:
Tread thread = new Thread();
To execute the thread, you can call the start() method of the thread:
thread.start();
In the above example, we did not Write the running code for the thread, so the thread terminates after calling this method.
There are two ways to write code that is executed when a thread is running: one is to create an instance of the Thread subclass and override the run method, and the second is to implement the Runnable interface when creating the class. Next we will explain these two methods in detail:
Create a subclass of Thread
Create an instance of the Thread subclass and override the run method. The run method will call the start() method be executed afterwards. Examples are as follows:
public class MyThread extends Thread { public void run(){ System.out.println("MyThread running"); }}
You can create and run the above Thread subclass in the following way
MyThread myThread = new MyThread();myTread.start();
The start method will return immediately once the thread is started, without waiting for the run method to complete execution. . It is as if the run method is executed on another CPU. When the run method is executed, the string MyThread running will be printed.
You can also create an anonymous subclass of Thread as follows:
Thread thread = new Thread(){ public void run(){ System.out.println("Thread Running"); }};thread.start();
When the run method of the new thread is executed, the computer will print out the string "Thread Running".
Implementing the Runnable interface
The second way to write thread execution code is to create a new instance of a class that implements the java.lang.Runnable interface. The methods in the instance can be called by the thread. An example is given below:
public class MyRunnable implements Runnable { public void run(){ System.out.println("MyRunnable running"); }}
In order to enable the thread to execute the run() method, the instance object of MyRunnable needs to be passed in the constructor of the Thread class. An example is as follows:
Thread thread = new Thread(new MyRunnable());thread.start();
When the thread is running, it will call the run method that implements the Runnable interface. In the above example, "MyRunnable running" will be printed.
Similarly, you can also create an anonymous class that implements the Runnable interface, as shown below:
Runnable myRunnable = new Runnable(){ public void run(){ System.out.println("Runnable running"); }}Thread thread = new Thread(myRunnable);thread.start();
Create a subclass or implement the Runnable interface?
There is no definite answer as to which of the two methods is better, they can both meet the requirements. In my personal opinion, I prefer to implement the Runnable interface. Because the thread pool can effectively manage threads that implement the Runnable interface, if the thread pool is full, new threads will be queued for execution until the thread pool is free. If threads are implemented by implementing a Thread subclass, this will be more complicated.
Sometimes we have to combine the two ways of implementing the Runnable interface and the Thread subclass at the same time. For example, an instance that implements a Thread subclass can execute multiple threads that implement the Runnable interface. A typical application is the thread pool.
Common mistake: calling the run() method instead of the start() method
A common mistake made when creating and running a thread is to call the thread's run() method instead of the start() method , as shown below:
Thread newThread = new Thread(MyRunnable());newThread.run(); //should be start();
At first you won’t feel anything wrong, because the run() method is indeed called as you expected. However, in fact, the run() method is not executed by the new thread just created, but by the current thread that created the new thread. That is, executed by the thread that executes the above two lines of code. If you want the created new thread to execute the run() method, you must call the start method of the new thread.
Thread name
When creating a thread, you can give the thread a name. It helps us differentiate between different threads. For example: If multiple threads write to System.out, we can easily find out which thread is outputting through the thread name. An example is as follows:
MyRunnable runnable = new MyRunnable();Thread thread = new Thread(runnable, "New Thread");thread.start();System.out.println(thread.getName());
It should be noted that because MyRunnable is not a subclass of Thread, the MyRunnable class does not have a getName() method. You can get the reference of the current thread in the following way:
Thread.currentThread();
Therefore, you can get the name of the current thread through the following code:
String threadName = Thread.currentThread().getName();
Thread code example:
Here is a small example . First, output the name of the thread executing the main() method. This thread is allocated by the JVM. Then start 10 threads and name them 1~10. Each thread exits after outputting its own name.
public class ThreadExample { public static void main(String[] args){ System.out.println(Thread.currentThread().getName()); for(int i=0; i<p>It should be noted that although the order of starting threads is orderly, the order of execution is not orderly. In other words, thread No. 1 is not necessarily the first thread to output its name to the console. This is because threads execute in parallel rather than sequentially. The Jvm and the operating system determine the execution order of threads, and it is not necessarily consistent with the startup order of threads. </p><p>Related recommendations: </p><p><a href="http://www.php.cn/java-article-380058.html" target="_self">Simple code example of Java thread-safe counter</a></p><p>##Instance analysis of synchronization and asynchronousness of objects in Java threads <a href="http://www.php.cn/java-article-374963.html" target="_self"></a></p><p>Wait/notify for communication between Java threads<a href="http://www.php.cn/java-article-368644.html" target="_self"></a></p>
The above is the detailed content of Methods to create and run java threads. For more information, please follow other related articles on the PHP Chinese website!

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


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

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.