Java Multithreading
Process: an independent unit of the system for resource allocation and scheduling
Threads: Subtasks that run independently in a process use Multithreading: Multithreading is asynchronous
Thread start order is independent of start () execution order
Non-thread safe: When multiple threads operate on the same instance variable in the same object, the value is changed and the value is not synchronized, which in turn affects the execution process of the program.
Workaround: Add the Synchronized keyword before the Run method to allow multiple threads to process the run method in a queued manner
public class Mythread extends thread{
private int count = 5;
@Override
synchronized public void Run () {
super.run ();
count--;
System.out.println ("by" +this.currentthread (). GetName () + "computed, count=" +count);
}
Stop Thread
There are three ways to terminate a running thread in Java: Use the exit flag to cause the thread to exit normally, that is, when the Run method completes, the thread terminates using the Stop method to force the thread to terminate (not recommended) because the stop is the same as the suspend and resume as the expiration method. Using them can produce unpredictable results use the interrupt method to disconnect threads
To determine whether a thread is stopped, there are two methods in the thread class: This.interrupted (): Tests if the line has been interrupted and has a feature that has the status flag set to the purge State (false) after execution this.isinterrupted () : Test thread is interrupted, do not clear status flag suspend thread
Suspend () method pauses the thread, resume () method restores the execution of the thread
Disadvantage: exclusive, using the Suspend and resume methods, if used improperly, it is easy to create a common synchronization object exclusive, so that other threads can not access the common synchronization object is not synchronized, easy to occur because the thread of the pause and cause the data is not synchronized yield method
The yield () method is to discard the current CPU resources, give it to other tasks to occupy CPU execution time, but give up the time is uncertain, may just give up, and immediately get the CPU time slice thread priority CPU priority to perform tasks in higher priority thread objects, Set thread priority use the SetPriority () method, the value is 1~10 thread priority has inheritance, such as a thread start B thread, then B thread priority and a thread is the same priority has a certain regularity, that is, the CPU as far as possible to give execution resources to higher priority threads Priority has a random daemon thread
There are two threads in a Java thread, one is a user thread and the other is a daemon
A daemon is a special thread whose attributes have the meaning of "companionship," which is automatically destroyed when no non-daemon threads exist in the process. A typical daemon is a garbage collection thread object and a variable's concurrent access synchronized the variable within the method method is thread safe (the method has a private variable) multiple locks can be locked and you can get their own internal locks again Exception, lock automatic release synchronization does not have inheritance synchronized synchronous statement block
Using keyword synchronized to declare a method can be a disadvantage in some cases, such as a thread calling the synchronization method to perform a long task, then the B thread must wait for a longer time
synchronized Synchronous code block use: when two concurrent threads access the synchronized (this) synchronized code block in the same object objects, only one thread can be executed for a period of time. Another thread must wait until the current thread finishes executing the code block before executing the code block.
That is, in the synchronized block is synchronous execution, not in the synchronized block is asynchronous execution, which can improve operational efficiency
When using the synchronized (this) code block, it is necessary to note that when one thread accesses a synchronized (this) synchronized code block of object, the other threads all other synchronized in the same object (this) The access to the synchronized code block will be blocked, indicating that the object monitor used by synchronized is a
The sync synchronized (this) code block is the one that locks the current object
In addition to synchronizing blocks of code using the synchronized (this) format, Java also supports the ability to synchronize "arbitrary objects" as object monitors, most of which are arguments to instance variables and methods, using a format of synchronized ( Non-this object x 1) When multiple threads hold the object monitor as the same object, only one thread at a time can execute code in the synchronized (non-this object x) Sync code block-When multiple threads execute synchronized (x) {} Synchronizing code blocks in sync Effect 2 when you hold object monitor as the same object, only one thread at a time can execute code in the synchronized (non-this object x) Sync code block-- Synchronous effect 3 When other threads perform the synchronized synchronization method in the X object the lock non-this object has some advantages: if there are many synchronized methods in a class, it can be synchronized but blocked, thus affecting operational efficiency. However, if you use a synchronized code block to lock a non-this object, the program in the synchronized (not this) code block is asynchronous and does not compete with the other lock this synchronization method for this lock, which can greatly improve operational efficiency- Synchronous effects are also rendered when other threads execute the synchronized (this) code block inside the X object method synchronized method and synchronized (class) code block
Keyword synchronized can also be applied to static statics, which is equivalent to holding locks on the class class corresponding to the current *.java file, and class locks can work on all object instances of the class
Synchronous synchronized (Class) block of code acts as a synchronized static method with multiple thread deadlocks
Deadlock: Different threads are waiting for locks that cannot be freed at all, causing all tasks to fail to complete
When multiple threads hold a lock object at the same time, if they hold the same lock object, the threads are synchronized, otherwise the volatile keyword is asynchronous
The primary role is to make the variable visible between multiple threads, and the keyword volatile forces the value of the variable to be taken from the public stack, rather than getting the value of the variable from the thread private data stack
public class Runthread extends Thread {
volatile private Boolean isrunning = true;
public boolean isrunning () {return
isrunning;
}
public void Setrunning (Boolean isrunning) {
this.isrunning = isrunning;
}
@Override public
Void Run () {
System.out.println ("Enter Run");
while (isrunning = = True) {
}
System.out.println ("Thread is stopped.") ");
}
}
public class Run {public
static void Main (string[] args) {
try{
runthread thread = new Runthread ();
Thread.Start ();
Thread.Sleep (1000);
Thread.setrunning (false);
SYSTEM.OUT.PRINTLN ("Already assigned to false");
} catch (Interruptedexception e) {
e.printstacktrace ();}}}
Volatile has a non atomic character that can cause thread insecurity, either by using the Synchronized keyword to implement synchronization or by using the Atomicinteger Atomic class for implementation
Private Atomicinteger count = new Atomicinteger (0);
...
Count.incrementandget ()//self-Increase 1
synchronized code blocks have volatile synchronization capabilities
Keyword synchronized enables multiple threads to access the same resource with synchronization, and it also has the ability to synchronize private variables in thread working memory with variables in public memory