Get the App
SLTechnology News&Howtos  ›  Development  › 

Solution to the problem of multithreading in java

Shulou Source: shulou.com Published: 2022-06-02 20:47:31 11月09日 Update

This article shows you the solution to the problem of java multithreading, which is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

See a multi-threaded topic on iteye, with reference to the implementation of netizens, then Eclipse debugging passed, can be regarded as a general understanding of the concurrent library of JAVA5, share it, welcome the students in the park to beat bricks.

Title:

It is required to use three threads to print 1, 2, 3, 4, 5 in order. 71,72,73,74, 75.

Thread 1 prints 1, 2, 3, 4, 5, 2, 6, 7, 8, 9, 10, and then thread 3 prints 11, 12, 13, 14, 15. Then thread 1 prints 16, 17, 18, 19, 20. And so on until thread 3 prints to 75.

Analysis: I feel that the person who asks the question is to see if you can control the multithreading well and let them proceed in an orderly manner.

1. Thread pool: 3 threads, which need to use the thread pool of the concurrent library

2. Lcok: when printing, only one thread is allowed to enter, while other threads wait

The following is the main code:

Import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class NumberPrinter {private Lock lock = new ReentrantLock (); private Condition C1 = lock.newCondition (); private Condition c2 = lock.newCondition () Private Condition c3 = lock.newCondition (); private Map condtionContext = new HashMap (); public NumberPrinter () {condtionContext.put (Integer.valueOf (0), C1); condtionContext.put (Integer.valueOf (1), c2); condtionContext.put (Integer.valueOf (2), c3);} private int count = 0 Public void print (int id) {lock.lock (); try {while (count*5 < 75) {int curID = calcID (); if (id = = curID) {for (int I = 1; I)

Tags: Thread problem solution three content skill knowledge order conciseness and so on succinct one code task classmate that is feeling number Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Xiaomi Shulou Information Huawei NVidia