----Multi-threaded communication-----
1. Overview: Multiple threads work on the same resource, but their tasks are different
Eg: thread 1 is responsible for storing data, and thread 2 is responsible for processing that data. Data--is the same resource
How to describe the above example in the Java language:
* Resources are variable-the data is changing-encapsulate it as an object
* There are two different threads for the task, 2 run methods required--so encapsulated in two different thread classes
* Must ensure that the input and output processing is the same object-input and output construction method parameters (parameter is a resource object reference)
* Main function inside, create resource object, Thread class object, start thread
2. Thread-safe issues with multithreaded communications
Workaround-Sync, sync in storage resources, but still error-ensure synchronization is required
Think about the premise of synchronization: The same lock-Multiple threads: Synchronizing a lock on both input and output threads to ensure synchronous implementation
Note: A certain analysis of the results: input threads get execution, constant assignment (switch), wait until
After the slice ends, the execution is executed to the output thread, and then the output thread is executed for a period of time, resulting in a large output phase
The appearance of the same situation
3. Thread wait and wake mechanism (important)----control input thread and output thread cooperation
Input-Determine if there is data-no input, there is wait (there is execution-to release execution and execution eligibility)-blocking and
Wake each other wait () +notify ()
Output-Determine if there is data-then take it out, no wait (there is execution-to release execution and eligibility)-Block and
Wake each other wait () +notify ()
Input thread and output thread wake each other, blocking is self blocking
The approach involved:
Wait (): threads are blocked and wait threads are stored in the online pool
Notify (): Wakes up any thread inside the thread pool
Notifyall (): Wakes up all threads inside the thread pool-makes threads eligible for execution
Attention:
1. These methods must be defined in synchronization, as these methods are used to manipulate the state of the thread, and must be clarified
The operation is the locked thread (wait/notify controls the thread within a lock range).
So the call to the Wait/notify method must be called by a thread corresponding to the lock: r.wait/notify
2.wait/notify is the method defined in object (cause: These methods are the method of the monitor, the monitor can be
Any object, so defined in object), that is used to manipulate the thread on the specified monitor.
3.wait--throws interruptedexception
4. The data for the resource should be private, provide access to external methods (to ensure the synchronization of resource data, wake-up congestion control);
The thread body only calls these methods, and does not require additional processing of thread safety and sequential control
Locked in there--wait, notify right there.
5. Note: If is for true execution, after wait, the contents of run no longer continue to execute down
----wait for the application of wake-up mechanism----producer consumer problem-----
Code simulates a producer--a consumer
1.Rescource
2.Producer
3.Consumer
Code simulation multi-producer (T0,T1)-Multi-consumer (T2,T3)
Multi-production and multi-consumption will cause the error---T0 wake up T1, T1 directly do not mark the judgment of direct production, resulting
The previous product was not consumed and a new product was produced. Improved if judgment changed to a while loop, which could cause death
Lock, T0,t1,t2,t3 are in a blocking state. The improvement wants to guarantee to wake up each other, had to use Notifyall method, Wake up
There are blocked methods, the side of the living, will judge not blindly production, the other side alive, can solve the deadlock.
Note: Use if to judge, will only be judged once, will cause the wrong thread to run, resulting in data errors
Using the Notify method: Just randomly wakes up a thread, which may be the thread of this party, which leads to a deadlock
Use while loop--to ensure that threads are executed after the thread is awakened
Use Notifyall () to resolve deadlocks to ensure that the wake-up thread contains the opposing thread
Multi-production multi-consumption use While+notifyall (inefficient, wake-up party to be judged)
New Tool-java.util.concurrent.locks Package (contains classes and interfaces)--an alternative to synchronized
The JDK1.5 is then encapsulated as an object, and the implicit definition of the action lock is encapsulated into the object, which is implicitly changed to the display
Try-catch-finally (the mutex must be released)
New Tool Lock interface (alternative synchronized related) +condition interface (Package Await/single/singleall method
) combined with. A lock object--can be accompanied by multiple sets of wait-wakeup methods
Lock lock = new Reeectrantlock ();
Condition C1 = Lock.newcondition ();//lock lock Object--Two group monitor method
Condition C2 = lock.newcondition ();
Previous deadlocks--no waking up to each other, or just going to wake up all (a group monitor method monitors the producer consumer)
Now, after the improvement, two sets of monitor methods are used to monitor the producers and consumers to ensure mutual wake-up
A summary of the new tools:
Lock interface: The reason for this is to replace the synchronous code block/synchronization method to change the implicit lock operation to the displayed lock
Operation, while being more flexible, you can add multiple sets of monitors to a lock object
Condition interface: There is an alternative to the Wait/notify/notifyall method inside the object, and these monitor methods
Individually encapsulated to become condition monitor object, can be combined with any lock object
The corresponding monitor method changes to: Await/singal/singalall
---wait/sleep difference----(important)
1.wait can specify time, can not specify time, sleep must specify time
2. Different CPU execution and lock handling in synchronization
After the thread wait, release the execution, release the lock (must be awakened not active wakeup)
After the thread is sleep, the execution is released, but the lock is not released
3.to,t1,t2 are waiting in sync and release execution and execution and lock, T4 wake up all threads, T0,T1,T2, this
is awakened in sync, but does not have execution, because T4 also holds locks, T4 release locks after execution
, a thread in one of the 3 threads that was awakened was dispatched by the CPU, acquiring the lock to start executing the thread's contents.
Essence: In synchronization, only the thread holding the lock can run
Stop-------for-----thread
1.stop Method-outdated presence of unsafe (forced termination of thread)
2.run method terminates normally after execution (usually with loops in it)
3. The use of multithreading is the solution, Some code in the program executes too much at this time, affecting the execution of the following code, so
usually put the loop inside the thread, the following code in the main thread inside, let them execute concurrently, can improve the efficiency
-----How to control the end of a thread task---
Task has a looping structure, You can end a task as long as you control the loop.
Control loops: typically use define conditional mark completion
to provide a way to expose the modified tag value externally, and call the method in the main thread to stop the thread
4. How to stop a thread in sync (thread is frozen-no chance to read the tag)
Interrupt Method--when a method called sleep,wait is frozen, the call to the interrupt method clears the state of the
break-the frozen state of the thread becomes operational (interrupt-is a frozen state)
The interrupt state is cleared: The thread state is changed from frozen to executable
Interrupt Method--throws interruptedexcption (wakes up thread when threads should not wake up)-Remember to handle
the exception. Modify the tag
notify--can only wake wait method
interrupt--forced Wake-A break exception must occur
Eg: a kiss wake-up--notify
A good wake up call---Interrupt
End Process: It is forced to end the thread inside the process and free the memory space
system-level process users cannot end
----Other common threading methods in a thread----
Setdaemon () Cheng the thread as a daemon, all running threads are daemons, the JVM stops running
Use time: Called before starting the thread
Background thread: Starting to run the same, ending differently, the foreground thread must end manually, and the background thread can be in the foreground thread
After the end, it ends automatically. The background thread is attached to the foreground thread.
Join (); After the thread calls the method (called in the main thread), the main thread releases the execution and execution eligibility, allowing the thread to execute
After that, the thread terminates normally, the main threads are eligible for execution, and other threads seize execution
Typically used to temporarily join threads--operations
SetPriority (): Sets the priority of the thread, not the higher the priority must be executed first, but the probability of being executed freshman
Some, 1-10, define the common priority 1,5,10 as static constants.
ToString (): Thread object has a corresponding string representation
Yield (): Active release of execution, next time and other threads seize execution-static method
Create a shortcut to a thread: Using an anonymous inner class
Java Basics Summary-Multithreading Summary 2