SoFunction
Updated on 2025-03-08

A brief discussion on the advantages and code examples of Java multithreading

Despite many challenges, multithreading has some advantages that make it always use. These advantages are:

Better resource utilization
Programming is simpler in some cases
The program responds faster
Better resource utilization

Imagine an application that needs to read and process files from a local file system. For example, it takes 5 seconds to read a file from disk and 2 seconds to process a file. To process two files, you need to:

5Read files in secondsA
2Process files in secondsA
5Read files in secondsB
2Process files in secondsB
---------------------
A total of14Second

When reading files from disk, most of the CPU time is spent waiting for disk to read data. During this time, the CPU was very idle. It can do something else. By changing the order of operations, you can better use CPU resources. Look at the following order:

5Read files in secondsA
5Read files in secondsB + 2Process files in secondsA
2Process files in secondsB
---------------------
A total of12Second

The CPU waits for the first file to be read. Then start reading the second file. When the second file is read, the CPU will process the first file. Remember that when you wait for the disk to read the file, the CPU is free most of the time.

In general, the CPU can do something else while waiting for IO. This is not necessarily disk IO. It can also be IO of the network, or user input. Normally, network and disk IO is much slower than CPU and memory IO.

Simpler programming

In a single threaded application, if you want to write a program to manually process the order of reads and processing mentioned above, you must record the status of each file reads and processing. Instead, you can start two threads, each processing the read and operation of a file. Threads will be blocked while waiting for disk to read files. While waiting, other threads can use the CPU to process the read files. The result is that the disk is always busy reading different files into memory. This will lead to improved disk and CPU utilization. Moreover, each thread only needs to record one file, so this method is also easy to implement.

The program responds faster

Another common goal of turning a single threaded application into a multi-threaded application is to implement a faster responsive application. Imagine a server application that listens for incoming requests on a certain port. When a request arrives, it processes the request and then returns to listen.

The server process is as follows:

while(server is active){
  listen for request
  process request
}

If a request takes a lot of time to process, the new client cannot send the request to the server during this time. The request can only be received when the server is listening. Another design is that the listening thread passes the request to the worker thread and then returns to listen immediately. The worker thread can process the request and send a reply to the client. This design is as follows:

while(server is active){
  listen for request
  hand request to worker thread
}

In this way, the server thread returns quickly to listen. Therefore, more clients can send requests to the server. This service has also become more responsive.
The same is true for desktop applications. If you click a button to start running a time-consuming task, which is both about executing the task and updating the window and buttons, then the application seems to have no response during the task execution. Instead, tasks can be passed to the worker thread. When the worker thread is busy processing tasks, the window thread can freely respond to other users' requests. When the worker thread completes the task, it sends a signal to the window thread. The window thread can update the application window and display the results of the task. For users, this kind of program with worker thread design appears to be more responsive.

The following is an example of Java multithreading drawn from someone else, thank you.

Question: 20 tickets are sold at the same time in three ticket windows;

Program Analysis:

1. The vote count should be used with the same static value
2. To ensure that the same number of votes are not sold, Java multi-threaded synchronization lock is required.

Design ideas: 1. Create a station class station, inherit Thread, rewrite the run method, and perform ticket sales operations in the run method! When selling tickets, you need to use a synchronization lock: that is, when there is a platform selling this ticket, the other platforms have to wait for the ticket to be sold out!

Create the main method call class

(I) Create a platform class and inherit Thread

(The original text has a little error, the editor has corrected it, please feel free to test and use it)

package ;
public class Station extends Thread {
	// Assign a value to the thread name through the constructor	public Station(String name) {
		super(name);
		// Assign a value to the thread name	}
	// In order to keep the votes consistent, the votes must be static	static int tick = 20;
	// Create a static key	static Object ob = "aa";
	//The value is arbitrary	// Rewrite the run method to realize the ticket buying operation	@Override
	public void run() {
		while (tick > 0) {
			synchronized (ob) {
				// This is very important, a lock must be used.				// The person who enters will hold the key in his hand and only let the key out after it comes out				if (tick > 0) {
					(getName() + "Sold" + tick + "Please vote");
					tick--;
				} else {
					("Tickets sold out");
				}
			}
			try {
				sleep(1000);
				//Rest for a second			}
			catch (InterruptedException e) {
				();
			}
		}
	}
}

(II) Create the main method call class

package ;
public class MainClass {
	/**
 * Use of Java multithreaded synchronization lock
 * Example: 10 tickets sold at the same time in three ticket windows
 * */
	public static void main(String[] args) {
		//Instantiate the platform object and name each platform		Station station1=new Station("Window 1");
		Station station2=new Station("Window 2");
		Station station3=new Station("Window 3");
		// Let each platform object start working		();
		();
		();
	}
}

Running results:

window1Sold20Ticket
window2Sold19Ticket
window3Sold18Ticket
window1Sold17Ticket
window2Sold16Ticket
window3Sold15Ticket
window3Sold14Ticket
window2Sold13Ticket
window1Sold12Ticket
window3Sold11Ticket
window2Sold10Ticket
window1Sold9Ticket
window1Sold8Ticket
window2Sold7Ticket
window3Sold6Ticket
window1Sold5Ticket
window3Sold4Ticket
window2Sold3Ticket
window3Sold2Ticket
window2Sold1Ticket
Tickets sold out

Summarize

The above is the entire content of this article about briefly discussing the advantages and code examples of Java multithreading. I hope it will be helpful to everyone. Interested friends can continue to refer to:Detailed explanation of the code of thread communication producer consumer model and waiting wake-up mechanism of Java multi-threadedJava programming: Multi-thread deadlock and communication between threads are simple codeJava multi-threaded programming small example simulates parking lot systemWait, if you have any questions, you can leave a message at any time, and the editor will reply to everyone in time. Thank you friends for your support for this site!