Sharing and operations between JAVA concurrent programming ----thread basis, thread

First, the basic concept  

1. What is the process and thread

The process is the smallest unit operating system for resource allocation, the next process can have multiple threads

The thread is the smallest unit of CPU scheduling, can not exist independently of the process, the process can share resources

Relations 2.CPU number of threads and cores

--cpu number of cores in general: the number of threads = 1: 1

After intel reference HyperThreading = 1: 2

3.CPU time rotation mechanism

Concurrent Programming CPU time slice rotation mechanism (RR scheduling) _Java_ Tan Qinghai -CSDN blog

4. Parallel and Concurrent

Parallel : while the number of tasks running

eg: a coffee machine capable of providing a service to the people, then it is a number of parallel, if two, then it is the number of parallel 2

Concurrency : a period of time capable of performing the task number

eg: a coffee machine in 10 minutes can produce two cups of coffee, then we can consider the number of concurrent concurrent within 10 minutes of 2

Thoughts: JAVA why the introduction of concurrent programming

1. make full use of CPU resources;

2. accelerate user response time;

Second, understanding in JAVA thread

JAVA in the thread is not preempted collaboration

1.java in the program is inherently multi-threaded, then start a new thread there are several ways?

Why java is inherently multi-threaded, so we prove it

public static void main(String[] args) {

// JAVA virtual machine threads System Management Interface

    ThreadMXBeanthreadMXBean= ManagementFactory.getThreadMXBean();

// get only a thread and the thread stack information

    ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(false,false);

for (ThreadInfo threadInfo : threadInfos) {

System.out.println("[" + threadInfo.getThreadId() +"]" + threadInfo.getThreadName());

}

}

After the run we will find on the console to print a lot of information to our thread (the thread information is for information only, not the point)

[8]JDWP Command Reader

[7]JDWP Event Helper Thread

[6]JDWP Transport Listener: dt_socket

[5] Attach Listener --- dump thread information Thread

[4]Signal Dispatcher

[3] Finalizer --- recycling target thread (daemon thread)

[2] Reference Handler --- reference recovery processing threads

[1] main --- the main thread main

Only one main method to print a lot of thread for us to explain our JAVA is inherently multi-threaded collaboration

Several new way to start a thread

JDK Thread notes provide source code

JDK tells us there are only two ways  

(1)extends Thread   

(2)implements Runnable

(. 3) the implements a Callable Note: Callable value is returned, and may be considered as a Runnable

The following is the code to achieve

public class Theadextends Thread {

@Override

    public void run() {

System.out.println ( "inherited from Thread");

}

}

public class Thead1implements Runnable {

@Override

    public void run() {

System.out.println("实现Runnable");

}

}

public class Thead2implements Callable {

@Override

    public Object call()throws Exception {

return "to achieve Callable";

}

}

So we say Thread and Runnable What difference does it make?

1.Thead is an abstraction of the thread, and Runable is an abstract task

2. If a class inherits Thread, not suitable for resource sharing. But if Runable implements the interface, then easily share resources.

3.main, an instance of the thread objects are different,

extends Thread :t.start();

implements Runnable : new Thread(t).start();

4. Use the Runnable, increasing process robustness, code can be shared by multiple threads, separate code and data

The thread pool can only achieve Runable into thread or callable class, not directly into the class inheritance Thread

2. very beginning the end, JAVA, how to make thread-safe stop it?

stop () or interrupt (), isInterrupted (), static method interrupted () => We need to understand these methods

stop () --- forced to stop the current thread

We can see the source code Thread stop method is marked obsolete label, which shows JDK tells us is not recommended, because it comes with positive action, and can not guarantee the safety and resource recovery thread

interrupt () --- thread notification interrupt (in fact, set the thread interrupt flag)

We can think of is to our thread say hello, to tell you the current thread to stop, but not for the forced break, decide whether to interrupt their own thread

isInterrupted () --- determine whether the current thread is interrupted 

It is generally used for determining whether operations in the thread run method

interrupted () --- a thread to interrupt flag

It can also be used to determine whether the thread has been interrupted, but will interrupt flag from true to false

* Needs to be performed Thread.currentThread () method used in the Runnable, to get the current thread, Runnable not provided in the above method

* When blocking method throws InterruptedException, the thread will not be interrupted, we need to manually re-call interrupt () method in the catch

* Threads in deadlock will not bother interrupted

Third, in Java thread a little bit more understanding

Thread of the life cycle

1. The state of the thread and thread common methods

In-depth understanding of run () and start ()

run () method for the thread executing the business method, after the execution of death

start () a thread into the ready state (executable state), each thread may be called only once, the waiting time slice rotation, when the cpu time allocated may enter the running state

Role wait () is to allow the current thread into a wait state, at the same time, wait () also makes the current thread releases the lock it holds. "Until another thread invokes the object's notify () method or the notifyAll () method", the current thread wakes up (into the "ready state")

Role notify () and notifyAll (), it is a wake up waiting threads on the subject of the current; notify () is to awaken a single thread, notifyAll () is a wake-up all the threads

wait (long timeout) so that the current thread in a "wait (blocking) state", "until another thread invokes the object's notify () method or the notifyAll () method, or a specified amount of time" and the current thread wakes up (to enter " ready state ")

Thread.yield Java thread () method, translated thread concessions. After the name suggests, that when a thread using this method, it will own CPU execution time to let out, let yourself or other threads running, is to pay attention to their own or other threads running, not simply to give other threads .

The role of yield () is a concession. It allows the current thread "running state" into a "ready state", so that other waiting threads with the same priority access to executive power; later, however, does not guarantee that the current thread calls yield (), the other with the same priority the thread will be able to get the implementation right; also possible that the current thread has entered into the "operating state" continues to run

The role of yield () is only let out cpu, does not make the lock

join () method, the execution right acquired, such that the thread can be executed sequentially, from the serial parallel changes

setPriority () method, set priorities, java priority level is divided into 1-10, default is 5, but can not guarantee priority thread execution order, the order is determined by the real cpu  

Daemon thread, a thread to the main thread perish, serving the main thread, such as GC threads, new Thread are users thread (non-daemon thread)

setDaemon (boolean on) set a daemon thread, the default is false, true daemon thread

* Note: Guardian thread finally does not necessarily play a role, upu time slice allocated to be implemented, it would not execute entirely determined by the operating system scheduler

Fourth, shared between threads

1.synchronized keyword (built-in lock)

Thread running, it has its own stack space, like a script as a step performed in accordance with established codes step until terminated. However, each running thread, if it is run in isolation only, then no little value, or worth very little, if multiple threads can cooperate with each other to complete the work, including the sharing of data among collaborative deal with things. This will bring tremendous value. Java support multiple threads access the member variables of an object or objects, keywords can be modified synchronized method or in the form of sync blocks to use, it is mainly to ensure that multiple threads at the same time, only one thread in a method or sync block, it ensures visibility and exclusive threads of variable access, also known as the built-in locking mechanism.

Objects and classes lock locks : lock an object for an object instance, or in the instance of an object, the object class lock is a static method on a class or a class for the class. We know that the class of object instances can be many, but each class has only one class object, the object lock a different object instances interfere with each other, but each class has only one class lock. But one thing must be noted that, in fact, there is just something like a lock on a concept that is not true, in fact, like lock lock is the corresponding class of objects of each class. Locks and the lock between objects are noninterfering

Usefulness and usage

(1) Method lock (synchronization method), sync blocks

public synchronized void incCount2() { count++;}

public void incCount3() { 

 synchronized (this) { 

 count++; 

 }

}

(2) object locking

private Objectobj = new Object (); // a lock as

public void incCount() { 

 synchronized (obj) { 

 count++; 

 }

}

(3) in the lock

public synchronized static void incCount4() { count++;}

* Note: synchronized lock object must ensure that the lock of the object can not be changed

Synchronization mechanism 2.volatile lightest

volatile ensure visibility when different threads to this variable operation, that is a thread modifies the value of a variable, this new value to other thread is immediately visible

volatile thread can not guarantee the safety of data written in multiple threads simultaneously

The most volatile applicable scenarios: a thread write, read multiple threads

3.ThreadLocal Analysis

(1) Compared with the Synchonized

ThreadLocal and Synchonized are used to solve multi-threaded concurrent access. But ThreadLocal and synchronized nature of the difference. synchronized using the lock mechanism, the variable code block at a time, or that only one thread can access. The ThreadLocal for each thread provides a copy of the variable so that each thread at a time to visit is not the same object, thus isolating the data shared by multiple threads of data

Spring's transaction will help the ThreadLocal class. Spring will get a connection from the database connection pool, and then put into a ThreadLocal connection, and there is a thread-bound

As long as the connection get operated from a ThreadLocal. Why Spring transaction must rely on ThreadLocal class? To JDBC, for example, a normal transaction code might look like:

 dbc = newDataBaseConnection (); // Line 1 

Connectioncon = dbc.getConnection (); // line 2

 con.setAutoCommit (false); //// Line 3 

con.executeUpdate (...); // line 4 

con.executeUpdate (...); // line 5 

con.executeUpdate (...); // line 6 

con.commit (); //// row 7 

The code can be divided into three parts: the transaction preparation phase: line 1 to 3 business processing stages: the first 4-6 rows transaction commits stage: line 7 can clearly see, whether we open the transaction or the implementation of specific sql We require a specific database connection. Now we have developed applications typically use the three-tier structure, if we control the affairs of the code under the DAO (DataAccessObject) object, in every way DAO object to open them and ending a transaction, when the Service object in the call DAO, If only a DAO call, so that we achieve the good results, but often our Service will call DAO a series of multiple operations on the database, then this time we can not control the affairs of the border, because the actual application, the number of DAO call our Service is uncertain, and may vary according to demand, but also the situation may arise Service call Service

Using (2) ThreadLocal of

ThreadLocal class interface is very simple, only four methods, let's take a look: 

• voidset (Objectvalue) set the value of the thread local variables of the current thread.

 • publicObjectget () method returns the thread-local variables corresponding to the current thread.

 • publicvoidremove () the value of the local variables of the current thread deleted, the purpose is to reduce memory usage, which is a new method for JDK 5.0. It should be noted that, when the end of the thread, the thread local variable should automatically be garbage, so explicitly call this method to clear the thread local variable is not required to operate, but it can speed up the recovery of memory speed.

 • protectedObjectinitialValue () returns the initial value of this thread-local variable, which is a protected method, apparently in order to allow subclasses cover design. This method is a method to delay calling, call get () or set (Object) when the execution thread the first time, and only performed once. The default ThreadLocal in direct returns a null.

publicfinalstaticThreadLocal <String> RESOURCE = new ThreadLocal <String> (); RESOURCE represents a ThreadLocal capable of storing objects of type String. At this time, no matter what one thread can concurrently access the variable, it is written to, read operations are thread safe.

 

The above is only represent the view of individual learning, we hope to provide a learning reference

 

Published 18 original articles · won praise 4 · Views 140

Guess you like

Origin blog.csdn.net/weixin_42081445/article/details/104828948