Java programming multi-thread problem example code, java multi-thread

Source: Internet
Author: User

Java programming multi-thread problem example code, java multi-thread

In the previous blog posts, I have summarized some content in java concurrency. This blog post mainly starts from a problem and shows which concurrency technologies can be used to solve the problem.

Description:

Simulate a scenario: It takes one second to process 16 log records. Normally, it takes 16 seconds to print these 16 records, now, to improve efficiency, we are ready to enable four threads for printing and print them in four seconds. This demo is implemented.

First, let's analyze this question. We can generate these 16 log records in the main thread, Which is useless. The key is to enable four threads for execution, there are two ideas: log generation and log printing threads are logically separated; the log generation and log printing threads are not logically separated. This may be a bit obscure. Below I will write an implementation demo to understand these two ideas.

Train of Thought 1

Log generation and log printing are logically separated.

This is equivalent to two fronts: one is constantly generating logs, and the other is constantly printing logs. It is obvious that you will think of blocking the use of the queue, generating logs that are constantly congested into the queue, printing logs that are constantly fetched from the queue, the size of the blocked queue can be set by yourself, you can set 16 or 1, which does not affect execution. So BlockingQueue is used. Let's take a look at the demo:

Public class Practice1 {public static void main (String [] args) {// define a blocking queue, the queue size can contain 16 pieces of information BlockingQueue <String> queue = new ArrayBlockingQueue <String> (16); for (int I = 0; I <4; I ++) {// enable four threads to block the log in the queue and print the new Thread (new Runnable () {@ Override public void run () {while (true) {try {String log = queue. take (); // get the log parseLog (log); // print the log} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}}). start ();} System. out. println ("begin:" + (System. currentTimeMillis ()/1000); for (int I = 0; I <16; I ++) {final String log = "" + (I + 1 ); // indicates a log try {queue. put (log); // plug the generated logs into the blocking queue} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} public static void parseLog (String log) {// Method for printing logs: System. out. println (Thread. currentThread (). getName () + "---" + log + "---" + (System. currentTimeMillis ()/1000); try {Thread. sleep (1000); // It takes 1 second to print a log simulation} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}

This is like a system that is running, while continuously generating logs, while enabling multiple threads to print log information, this demo is ready, and the running result is not pasted.

Train of Thought 2

Log generation and log printing are not logically separated.

This idea is that when I generate logs, you can print them out and work with four threads! In this case, the thread pool is used. When I create a thread pool, four threads are installed in it, and then logs are generated, I want this thread pool to execute it with a thread. The demo is as follows:

Public class Practice1 {public static void main (String [] args) {ExecutorService service = Executors. newFixedThreadPool (4); // create a thread pool System. out. println ("begin:" + (System. currentTimeMillis ()/1000); for (int I = 0; I <16; I ++) {final String log = "" + (I + 1 ); // upload a log service.exe cute (new Runnable () {// run @ Override public void run () {parseLog (log) ;}}) with a thread;} service. shutdown (); // do not forget to close the thread pool.} public static void parseLog (String log) {System. out. println (Thread. currentThread (). getName () + "---" + log + "---" + (System. currentTimeMillis ()/1000); try {Thread. sleep (1000); // It takes 1 second to print a log simulation} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}

To solve this problem, we can summarize the two ideas and solve them effectively.

Summary

The above is all the content of the sample code for a multi-thread problem in Java programming. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.