Write code to implement the following functions
The sub-thread loops for 10 times, the main thread loops for 100 times, and then returns to the sub-thread loop for 10 times, and then returns to the main thread for another 100 times, so that the loop is 50 times.
Analysis
1) the subthread must be mutually exclusive for 10 cycles and 100 cycles of the main thread, and there cannot be cross-execution. The following code uses the synchronized keyword to implement this requirement;
2) the subthread and the main thread must alternate. This can be achieved through synchronous thread communication technology. The following code uses the bShouldSub variable to implement this requirement;
Other notes
1) The business variable must be declared as the final type, because the local variables called in the anonymous internal class and local internal class must be final, so as to ensure:
-Consistency of variables (final variables will be copied as local internal class variables during compilation );
-Avoid inconsistency between the lifecycle of local variables and objects of local internal classes.
Otherwise,
-If the local variable is modified in the external class after it is passed into the local internal class, the value of this variable in the internal class is inconsistent with that in the external class, unpredictable situations may occur;
-Otherwise, the life cycle of local variables is cleared from the stack as the method ends, and a local internal class accesses a nonexistent variable.
If it is a member variable, it does not need to be final.
2) the internal category can be divided into four types: member Internal category, static internal category, local internal category, and anonymous internal category. For the life cycle and detailed usage of the four types, please ask Google or du Niang.
Code implementation
Public class TraditionalThreadCommunication {public static void main (String [] args) {// must be declared as final Business business = new Business (); new Thread (new Runnable () {@ Override public void run () {for (int I = 1; I <= 50; I ++) {business. sub (I );}}}). start (); for (int I = 1; I <= 50; I ++) {business. main (I) ;}} class Business {// this variable is used for inter-thread communication private boolean bShouldSub = true; public synchronized voi D sub (int I) {if (! BShouldSub) {try {this. wait ();} catch (InterruptedException e) {e. printStackTrace () ;}}for (int j = 1; j <= 10; j ++) {System. out. println ("sub thread sequence of" + j + ", loop of" + I);} bShouldSub = false; this. notify ();} public synchronized void main (int I) {if (bShouldSub) {try {this. wait ();} catch (InterruptedException e) {e. printStackTrace () ;}}for (int j = 1; j <= 100; j ++) {System. out. println ("main thread sequence of" + j + ", loop of" + I);} bShouldSub = true; this. notify ();}}
Java concurrency-Inter-thread communication and synchronization technology
This article introduces the concept and implementation of bounded cache, and introduces the necessity of inter-thread communication and synchronization technology in the process of implementing bounded cache step by step. First, we will introduce a bounded cache abstract base class. All specific implementations will inherit from this abstract base class:
Public abstract class BaseBoundedBuffer <V> {private final V [] buf; private int tail; private int head; private int count; protected BaseBoundedBuffer (int capacity) {this. buf = (V []) new Object [capacity];} protected synchronized final void doPut (V v) {buf [tail] = v; if (++ tail = buf. length) tail = 0; ++ count;} protected synchronized final V doTake () {V v = buf [head]; buf [head] = null; if (++ head = buf. length) head = 0; -- count; return v;} public synchronized final boolean isFull () {return count = buf. length;} public synchronized final boolean isEmpty () {return count = 0 ;}}
There is a problem when inserting or extracting elements into the bounded cache, that is, if the cache is full, still need to be inserted? If the cache is empty, what are the extracted elements? The following implementation will answer this question separately.
1. Pass the exception to the caller
The simplest way is to add an element to the cache when the cache is full:
Public class extends <V> extends BaseBoundedBuffer <V> {public GrumpyBoundedBuffer () {this (100);} public GrumpyBoundedBuffer (int size) {super (size );} public synchronized void put (V v) throws BufferFullException {if (isFull () throw new BufferFullException (); doPut (v);} public synchronized V take () throws BufferEmptyException {if (isEmpty () throw new BufferEmptyException (); return doTake ();}}
This method is easy to implement, but it is not easy to use, because every put () and take () must be prepared to catch exceptions, which may meet some requirements, however, some users still want to block the inserted object when it is detected that it is full.
2. Simple blocking through polling and sleep
When the queue is full and data is inserted, we can not throw an exception, but sleep the thread for a period of time and try again. At this time, the queue may not be full:
Public class SleepyBoundedBuffer <V> extends BaseBoundedBuffer <V> {int SLEEP_GRANULARITY = 60; public SleepyBoundedBuffer () {this (100);} public partition (int size) {super (size);} public void put (V v) throws InterruptedException {while (true) {synchronized (this) {if (! IsFull () {doPut (v); return ;}} Thread. sleep (SLEEP_GRANULARITY) ;}} public V take () throws InterruptedException {while (true) {synchronized (this) {if (! IsEmpty () return doTake ();} Thread. sleep (SLEEP_GRANULARITY );}}}
The biggest problem with this implementation method is that it is difficult to determine the appropriate sleep interval. If the sleep interval is too long, the program's responsiveness will deteriorate. If the sleep interval is too short, this will waste a lot of CPU time.
3. Use condition queue for bounded cache
The method of hibernation has a responsiveness problem, because we cannot guarantee that when the queue is not full, the thread will immediately sleep and detect it. Therefore, we hope to have another implementation method, when the cache is not full, the thread is automatically woken up, instead of waiting for the thread to poll the cache status. wait () and policyall () on the Object can meet this requirement. When the wait () method is called, the thread automatically releases the lock and requests the operating system to suspend the current thread. When other threads detect that the conditions are met, the notifyAll () method is called to wake up the suspension.
Public class BoundedBuffer <V> extends BaseBoundedBuffer <V> {public BoundedBuffer () {this (100);} public BoundedBuffer (int size) {super (size );} public synchronized void put (V v) throws InterruptedException {while (isFull () wait (); doPut (v); policyall ();} public synchronized V take () throws InterruptedException {while (isEmpty () wait (); V v = doTake (); policyall (); return v;} public synchronized void alternatePut (V v V) throws InterruptedException {while (isFull () wait (); boolean wasEmpty = isEmpty (); doPut (v); if (wasEmpty) policyall ();}}
Note: In the above example, we use the yyall () wake-up thread instead of the Y () wake-up thread. If we use notify () to wake up the thread, it will lead to an error, notify () A random thread will be selected in the waiting queue to wake up, while policyall () will wake up all the waiting threads. For the above example, if it is not in full state, we use notify () to wake up the thread. Since we can only wake up one thread, what we wake up may be waiting for a thread in non-empty state, this will cause signal loss. A single policy instead of policyall can be used only when both of the following conditions are met:
The types of all waiting threads are the same. There is only one condition predicate associated with the condition queue, and each thread will perform the same operation after returning from wait.
Single-in-single-out. Each notification on a condition variable can only wake up one thread for execution.
4. Use the displayed Condition to implement bounded cache
The built-in condition queue has some defects. Each built-in lock can have only one associated condition queue. Therefore, as in the previous example, multiple threads must wait for different Condition predicates on the same Condition queue. To write a concurrent object with multiple Condition predicates, you can use the displayed lock and Condition, different from built-in locks, each display lock can have any number of Condition objects. The following code provides another implementation of bounded cache, that is, two conditions, notFull and notEmpty, are used to represent the Condition predicates "not full" and "not empty.
Public class ConditionBoundedBuffer <T> {protected final Lock lock = new ReentrantLock (); private final Condition notFull = lock. newCondition (); private final Condition notEmpty = lock. newCondition (); private static final int BUFFER_SIZE = 100; private final T [] items = (T []) new Object [BUFFER_SIZE]; private int tail, head, count; public void put (T x) throws InterruptedException {lock. lock (); try {while (count = items. length) notFull. await (); items [tail] = x; if (++ tail = items. length) tail = 0; ++ count; notEmpty. signal ();} finally {lock. unlock () ;}} public T take () throws InterruptedException {lock. lock (); try {while (count = 0) notEmpty. await (); T x = items [head]; items [head] = null; if (++ head = items. length) head = 0; -- count; notFull. signal (); return x;} finally {lock. unlock ();}}}
Note: In the above example, because two Condition objects are used, our wake-up method calls the signal () method instead of the signalAll () method.
When using conditional queues, pay special attention to the ternary relationship between locks, condition predicates, and condition variables: variables contained in condition predicates must be protected by locks, when checking condition predicates and calling wait and policy (or await and signal), the lock object must be held.