1. Inherit the Thread class to implement multi-threading
- Step 1: Define thread class
Create a class inherits from the Thread class and override the run method. The code in the run method is the content executed by the thread.
For example:
class MyThread extends Thread { @Override public void run() { for (int i = 0; i < 10; i++) { ("MyThread: " + i); } } }
- Step 2: Start the thread
Create a thread object in the main method or other suitable place, and then call the start method to start the thread.
For example:
public class Main { public static void main(String[] args) { MyThread thread = new MyThread(); (); for (int i = 0; i < 10; i++) { ("Main Thread: " + i); } } }
Note that the run method cannot be called directly to start the thread. If the run method is called directly, it is equivalent to executing the code in the run method in the current thread, rather than opening a new thread.
2. Implement the Runnable interface to implement multi-threading
- Step 1: Define the task class
Create a class to implement the Runnable interface and implement the run method. This run method contains the tasks that the thread wants to execute.
For example:
java class MyRunnable implements Runnable { @Override public void run() { for (int i = 0; i < 10; i++) { ("MyRunnable: " + i); } } }
- Step 2: Create a thread and start it
First create the Runnable object, then pass it as a parameter to the constructor of the Thread object, and finally call the start method of the Thread object to start the thread.
For example:
public class Main { public static void main(String[] args) { MyRunnable runnable = new MyRunnable(); Thread thread = new Thread(runnable); (); for (int i = 0; i < 10; i++) { ("Main Thread: " + i); } } }
Advantages of implementing Runnable interface
This method is more flexible because a class can implement multiple interfaces, avoiding the limitation of single inheritance. For example, if a class has inherited other classes and wants to implement multi-threading functions, you can use the method of implementing the Runnable interface. Moreover, the Runnable object can be shared by multiple threads, making it easier to perform the same task in multiple threads.
3. Use Callable and Future to implement multi-threading (with return value)
- Step 1: Define Callable task class
Create a class to implement the Callable interface and implement the call method. The call method contains the task that the thread wants to execute and can have a return value.
For example:
import ; class MyCallable implements Callable<Integer> { @Override public Integer call() { int sum = 0; for (int i = 0; i < 10; i++) { sum += i; } return sum; } }
- Step 2: Submit the task and get the results
Submit Callable tasks through ExecutorService. ExecutorService can be created through the Executors factory class.
For example:
import ; import ; import ; public class Main { public static void main(String[] args) throws Exception { ExecutorService executorService = (); MyCallable callable = new MyCallable(); Future<Integer> future = (callable); ("Calculation result: " + ()); (); } }
Here, the submit method submits the Callable task and returns a Future object. The callable task return value can be obtained through the Future object get method. The shutdown method is used to close the ExecutorService.
4. Use of thread pool (ExecutorService)
- Step 1: Create a thread pool
You can use the Executors factory class to create different types of thread pools, such as newFixedThreadPool (fixed-size thread pool), newCachedThreadPool (cacheable thread pool), newSingleThreadExecutor (single-thread thread pool), etc.
For example, create a thread pool of fixed size 5:
ExecutorService executorService = (5);
- Step 2: Submit the task to the thread pool
You can submit Runnable tasks using the execute method, or submit Callable tasks to the thread pool using the submit method.
For example, submit a Runnable task:
class MyRunnableInPool implements Runnable { @Override public void run() { ("Threads in thread pool are executing tasks"); } } public class Main { public static void main(String[] args) { ExecutorService executorService = (5); for (int i = 0; i < 10; i++) { (new MyRunnableInPool()); } (); } }
- Step 3: Close the thread pool
When the task is executed, the thread pool needs to be closed. You can use the shutdown method to close the thread pool normally, it will wait for all submitted tasks to be executed before closing. If you want to close the thread pool immediately, you can use the shutdownNow method, but this method may cause the execution of the task to be interrupted.
For example:
();
Q: When will a Java project for management system need to use multi-threading?
1. Data import and export functions
Background and requirements:
In the management system, data import and export operations are often required. For example, import a large amount of user information, order data, etc. from external files (such as CSV, Excel files) into the database, or export data in the system into a report file. These operations may involve a large amount of data processing, and if executed in a single thread, it will cause the interface to be unresponsive for a long time and the user experience will be poor.
Multithreaded application method:
A separate thread can be enabled to perform data import or export tasks. In this way, while data processing, the user interface can still respond to other users' operations, such as viewing other data, performing system settings, etc. For example, when the user clicks the "Import Data" button, the system reads the file in the background thread, parses the data, and inserts it into the database, while the foreground thread continues to respond to other users' interactions.
2. Data cache update and maintenance
Background and requirements:
To improve system performance, management systems usually use data caches. The cached data needs to be updated regularly to ensure the consistency and timeliness of the data. For example, cached product inventory information, user permission information, etc. need to be updated based on the latest data in the database.
Multithreaded application method:
You can use a thread to periodically (such as every once in a while) to check whether the cached data expires and update the cache if needed. This thread can run silently in the background without affecting other major functions of the system. At the same time, when data changes (such as the user modified the product inventory), the cache can also be updated in time through a multi-threading mechanism to reduce the impact on other system operations.
3. Concurrent user operation processing
Background and requirements:
In a management system that is used by multiple users, multiple users will perform various operations at the same time, such as querying data, modifying records, submitting forms, etc. If the system is single-threaded, these operations can only be performed in sequence, which is inefficient.
Multithreaded application method:
Assign an independent thread to each user request to process. For example, in an online mall management system, when multiple administrators modify product prices and process orders at the same time, the system can open a thread for each administrator's operations, which can concurrently access and modify data in the database (of course, attention should be paid to the rational use of database connection pools and data consistency issues), thereby improving the system's concurrent processing capabilities.
4. System monitoring and logging
Background and requirements:
The management system needs to monitor its own operating status, such as system resource usage (CPU, memory, disk I/O, etc.), service availability, etc. At the same time, it is necessary to record user operation logs, system error logs and other information.
Multithreaded application method:
A thread can be used to specifically be responsible for system monitoring, regularly collect system status data and analyze it. Another thread can be responsible for writing log information into the log file, which can prevent logging operations from blocking other business operations, and can record relevant information in a timely manner when there is a problem in the system, which facilitates subsequent troubleshooting.
5. Timed task execution
Background and requirements:
There are many timed tasks in the management system, such as generating sales reports regularly every day, and setting up employee wages regularly every month. These tasks need to be automatically executed at a specific time and cannot affect the normal operation of the system.
Multithreaded application method:
Manage timed task threads through thread pools. For example, use ScheduledExecutorService in Java to schedule timing tasks. The system can automatically execute these tasks in background threads according to the execution time and frequency of tasks without interfering with the daily operations of the system.
Q: As long as you inherit the runnable interface, will multi-threading be enabled when using this class?
Inheriting the Runnable interface only defines the task content
When a class implements the Runnable interface, it simply defines the task logic that a thread wants to execute, which is contained in the run method.
For example:
class MyRunnable implements Runnable { @Override public void run() { ("Execute custom tasks"); } }
The above code defines a class named MyRunnable, which implements the Runnable interface, and the specific tasks to be executed in the run method. But at this time, the task is only defined and multi-threading has not been enabled.
You need to start a thread to execute tasks through the Thread class
To actually start a new thread to perform this task, you need to pass the Runnable object as a parameter to the constructor of the Thread class, and then call the start method of the Thread object. For example:
java public class Main { public static void main(String[] args) { MyRunnable runnable = new MyRunnable(); Thread thread = new Thread(runnable); (); } }
In this example, first create an object runnable of the MyRunnable class, and then create a Thread object through new Thread(runnable), which will perform tasks defined in the runnable object. Finally, call the() method to start the thread. If it was just created
Thread object without calling the start method, and the task will not be executed in a new thread, which is no different from ordinary method calls.
Therefore, simply inheriting the Runnable interface does not enable multi-threading. It only provides a convenient way to define the tasks to be executed by the thread. It also needs to actually start the thread through the Thread class to allow the task to run in a new thread environment.
Summarize
This is the article about the four methods and usage scenarios of JAVA multi-threading implementation. For more information about JAVA multi-threading implementation, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!