Java programming a multithreading problem example code

  • 2021-01-25 07:33:14
  • OfStack

The previous posts have basically summarized some of the content of java concurrency. This post starts with one problem and looks at what concurrency techniques can be used to solve it.

Title description:

[

Simulate 1 scenario: 16 log records are processed, and the printing time of each log record is 1 second. Under normal circumstances, it takes 16 seconds to complete the printing of these 16 records. Now, in order to improve the efficiency, we are going to start 4 threads to print and finish the printing in 4 seconds to realize this demo.

]

The 16 log records can be generated in the main thread, which is not difficult. The key is to start 4 threads to execute the log records. There are two ways to think about it: 1. One is that the log is generated from a thread that is not logically separate from the thread that prints the log. This may be a little obscure, but let me write an implementation of demo for both of these ideas.

Idea 1

Log generation and log printing are logically separated.

This is equivalent to two fronts: one front is constantly generating logs, and the other front is constantly printing logs. It is obvious to think about the use of blocking queues. The generated logs are constantly being pushed into blocking queues, and the printed logs are constantly being taken out of blocking queues. The size of blocking queues can be set by itself, which can be set to 16 or 1, and it does not affect execution. This is why BlockingQueue is used. Let's see the following implementation of demo:


public class Practice1 {
	public static void main(String[] args) {
		// define 1 The size of the queue can be installed 16 An information 
		BlockingQueue<String> queue = new ArrayBlockingQueue<String>(16);
		for (int i = 0; i < 4; i ++) {
			// open 4 A thread to block the queue from fetching log prints 
			new Thread(new Runnable() {
				@Override
				        public void run() {
					while(true) {
						try {
							String log = queue.take();
							// Take the log 
							parseLog(log);
							// Print log 
						}
						catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
			).start();
		}
		System.out.println("begin:" + (System.currentTimeMillis()/1000));
		for (int i = 0; i < 16; i ++) {
			final String log = "" + (i+1);
			// said 1 A log 
			try {
				queue.put(log);
				// Push the generated log into the blocking queue 
			}
			catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public static void parseLog(String log) {
		// A method to print the log 
		System.out.println(Thread.currentThread().getName() + "---"
		        + log + "---" + (System.currentTimeMillis()/1000));
		try {
			Thread.sleep(1000);
			// Simulation printing 1 Secondary log need 1 seconds 
		}
		catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

This is like a system in operation, 1 side is constantly generating logs, 1 side is constantly starting multiple threads to print log information, the demo is written, the results are not posted.

Idea 2

Log generation and log printing are not logically separate.

The idea is, as soon as I generate the log, you print it out for me, and 4 threads start working! So this idea, I'm going to use a thread pool, I'm going to create a thread pool, I'm going to have four threads in it, and then when the log is generated, I'm going to have this thread pool take the thread and execute it. demo is as follows:


public class Practice1 {
	public static void main(String[] args) {
		ExecutorService service = Executors.newFixedThreadPool(4);
		// create 1 A thread pool 
		System.out.println("begin:" + (System.currentTimeMillis()/1000));
		for (int i = 0; i < 16; i ++) {
			final String log = "" + (i+1);
			// said 1 A log 
			service.execute(new Runnable() {
				// take 1 To be executed by a thread 
				@Override
				        public void run() {
					parseLog(log);
				}
			}
			);
		}
		service.shutdown();
		// Finally, don't forget to turn off the thread pool 
	}
	public static void parseLog(String log) {
		System.out.println(Thread.currentThread().getName() + "---"
		        + log + "---" + (System.currentTimeMillis()/1000));
		try {
			Thread.sleep(1000);
			// Simulation printing 1 Secondary log need 1 seconds 
		}
		catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

About this problem, summed up to this, the two ways of thinking clear 1 can be effectively solved.

conclusion

Above is this article about Java programming 1 multithreading problem example code of all content, hope to help you. Interested friends can continue to refer to the site of other related topics, if there are shortcomings, welcome to leave a message to point out. Thank you for your support!


Related articles: