Thread Java Thread object lock, class lock, thread safety

Source: Internet
Author: User
Tags thread class

Description:

1, personal technology is not a drop, also did not write threads in the project, the following are all based on their own understanding of the written. Therefore, only for reference and hope to point out the different views.

2, actually want to put the code of GitHub posted out, but still recommended in the beginner you write more personally, it is not posted out.

I. BASIC INSTRUCTIONS

Class, Object: ... (Don't know what to say, imaginative achievement here inexpressible >.<!); Understand which methods, variables are objects, and which are classes.

Class locks, Object locks: corresponding classes and objects. Each class has and has only one class lock, and each object has only one object lock.

Ex:person P1 = new Person (); person P2 = new person ();

The person class has only one class lock, the P1 object has its own object lock, and P2 also has its own object lock. Therefore, the demo has a total of 3 locks: 1 lock class, 2 object locks.

Process, Thread: a process can have multiple threads.

concurrency : maximize resources and take turns. Ex: There is only one "Think in Java", a look at a B for a while.

parallel : True simultaneous, ex: There are many "Think in Java", a look at a book, b read a book.

Excerpt from Baike:

The essence of concurrency is that a physical CPU (or multiple physical CPUs) is multiplexed across several programs, and concurrency is forcing multiple users to share a limited physical resource to increase efficiency.

Parallelism refers to the occurrence of two or more two or more events or activities at the same time. In a multi-channel program environment, parallelism enables multiple programs to execute simultaneously on different CPUs at the same time.

What I know is that threads in Java, or threads that are normally said, are basically concurrent (I'm not sure, because it's not clear; in front of Baidu, the basic blog that the Java implementation of parallelism is actually concurrency, but also see that JDK8 can be parallel programming, to understand).

Second, the scene concept

Scenario: (Regardless of thread safety, known constraints per output 0~4)

To output 0, 1, 2, 3, 4 total 3 times, that is, the total output 15 times.

Realize:

1, (class Lock) 3 objects are executed 1 times each.

2, (object Lock) An object is executed 3 times.

III. implementation of 1:3 objects executed 1 times

1, now regardless of thread safety, do not consider synchronous asynchronous, only simple to meet: 3 of the objects are executed 1 times each.

 Public classClasslock { Public Static voidMain (string[] args) {Runnable async =NewAsyncclass (); Thread T1 =NewThread (Async, "thread-a"); Thread t2 =NewThread (Async, "Thread-b"); Thread t3 =NewThread (Async, "thread-c"); T1.start ();//Code-1T2.start ();//Code-2T3.start ();//Code-3}}/** Relative Async * /classAsyncclassImplementsrunnable{@Override Public voidRun () { for(inti = 0; I < 5; i++) {Try{//Thread.Sleep (1*1000);System.out.println (Thread.CurrentThread (). GetName () + " : "+ i); }Catch(Exception e)            {E.printstacktrace (); }        }    }}

Special IMPORTANT NOTE:

1, Java thread scheduling is random, what meaning?

In the above code, only T1, T2, T3 are guaranteed to execute, but the order of the output cannot be determined. The following examples illustrate several:

(Personal understanding, may understand/Word error) Java code is executed sequentially, so you can ensure that T1, T2, T3 enter the thread pool (the word is bad, or similar to the waiting room, waiting to acquire the lock) order in code order. However, the fetch lock is random (JVM determined).

In the reference code, the process process-a open thread Thread-main to execute the main method. There is only one thread at this time: Thread-main.

When the thread thread-a is turned on when executing to Code-1, PROCESS-A has 2 threads: Thread-main, Thread-a.

Because there are multiple threads, there is a problem with thread scheduling now process-a. That is, it is possible to continue with the code behind main, or to execute the THREAD-A code. Or rotate execution, that is, concurrency.

Later, there are 3 threads executed to code-2: Thread-main, Thread-a, Thread-b.

 Public Static void Main (string[] args) {    new asyncclass ();    New Thread (Async, "thread-a");    New Thread (Async, "thread-b");    New Thread (Async, "thread-c");    System.out.println ("Vergilyn");    T1.start ();    System.out.println ("Dante");    T2.start ();    System.out.println ("Vergil");    T3.start ();    System.out.println ("end");}

The result of the above code: only "Vergilyn" is guaranteed to be the first output, the subsequent output sequence is indeterminate (including end).

2, (synchronous class lock) Now ensure that an object output is finished, another object is then output

Because 3 objects are executed individually, the class lock is used instead of the object lock. (Synchronous static method plus is equivalent to class lock)

/** Sync * /classSyncClassImplementsrunnable{@Override Public voidRun () {synchronized(SyncClass.class){//sync-1             for(inti = 0; I < 5; i++) {//synchronized (syncclass.class) {//sync-2                    Try{//Thread.Sleep (1*1000);System.out.println (Thread.CurrentThread (). GetName () + " : "+ i); }Catch(Exception e)                    {E.printstacktrace (); }//  }}        }    }}

Description: Because it is a class lock, it is guaranteed that each object comes in and must execute the for loop before releasing the class lock (you can also manually release Wait (): Release the lock, other threads can compete to acquire the lock; sleep (): No lock is released, ownership of the lock or the current thread)

1, Sync-1 can meet the demand. Ensures that the lock is released only after the For loop is executed.

2, sync-2 when the execution of the Try-catch to release the lock, the thread between the competition to acquire the lock, and can not determine which thread to obtain the next lock.

In multi-threading, the important point is: the choice of the synchronization block (where is the minimum synchronization block, or the synchronization block is correct), synchronization affects concurrency.

In the above demo in fact, the example is not good, to achieve the demand can only be written in Sync-1, and not written in Sync-2. But what this means is that you have to be clear about what you want to lock, whether it's an object or a class. Where is the minimum synchronization code block?

Iv. Implementation 2: One object executes 3 times
 Public classObjectlock { Public Static voidMain (string[] args) {Runnable P1 =NewSyncObject ();//Runnable P1 = new Asyncthread ();Thread T1 =NewThread (P1, "A"); Thread t2 =NewThread (P1, "B"); Thread t3 =NewThread (P1, "C");        T1.start ();        T2.start ();    T3.start (); }}classAsyncobjectImplementsrunnable{@Override Public voidRun () { for(inti = 0; I < 5; i++) {Try{//Thread.Sleep (1*1000);System.out.println (Thread.CurrentThread (). GetName () + " : "+ i); }Catch(Exception e)            {E.printstacktrace (); }        }    }}classSyncObjectImplementsrunnable{@Override Public voidRun () {synchronized( This){ for(inti = 0; I < 5; i++) {Try{//Thread.Sleep (1*1000);System.out.println (Thread.CurrentThread (). GetName () + " : "+ i);
                Catch (Exception e) {                    e.printstacktrace ();}}}}}    

In the demo, there is very little difference between the code and the class lock. It is nothing more than three objects bound by one thread execution, or an object bound three threads executed (bad words)

Five, object lock, Class lock

I do not know how to express in words, I hope through the above code can realize what is a lock, what is Object lock, class lock.

The function of a lock is that the thread holding the lock can execute, and the other thread can only wait to acquire the lock. (again: The JVM randomly determines who can acquire the lock.) )

Extended:

The thread holding the lock releases the lock:

1. Execute the synchronization code block.

2. During the execution of a synchronous code block, an exception is encountered that causes the thread to terminate.

3. During the execution of a synchronous code block, the Wait () method of the object to which the lock belongs is executed, which releases the lock and enters the object's waiting pool.

In addition to the above, locks are not released as long as the thread holding the lock has not finished executing the synchronization code block.

The thread does not release the lock:

1. During the execution of the synchronization code block, the Thread.Sleep () method is executed, the current thread discards the CPU, starts to sleep, and does not release the lock during sleep.

2. During the execution of the synchronization code block, the Thread.yield () method is executed, and the current thread discards the CPU but does not release the lock.

3. During the execution of a synchronous code block, other threads execute the Suspend () method of the current object, and the current thread is paused, but the lock is not released. But the suspend () method of the thread class has been deprecated.

VI. Thread SAFETY

Excerpt from Baike:

Thread Safety is a multi-threaded access, with a locking mechanism, when a thread accesses one of the class's data, protection, other threads can not access until the thread is finished reading, other threads are available. There is no data inconsistency or data contamination. thread Insecurity is not providing data access protection, it is possible that multiple threads change the data successively, causing the resulting data to be dirty data.

For example a ArrayList class, when adding an element, it may have two steps to complete: 1. This element is stored in the location of Items[size]; 2. Increase the value of Size.

In the case of single-threaded runs, if Size = 0, after adding an element, this element is at position 0, and size=1;

In the case of multithreading, such as having two threads, thread A first stores element 1 in position 0. However, when CPU scheduler thread a pauses, thread B gets the chance to run. Thread B adds element 2 to this ArrayList, since Size is still equal to 0 (note that we assume that adding an element is two steps, and thread a just completes step 1), so thread B also stores the element in position 0. Then both thread A and thread B continue to run, increasing the value of size, resulting in size equal to 2.

Well, let's take a look at the situation of ArrayList, the expected element should have 2, and actually only one element, resulting in the loss of elements, and size equals 2. This is "thread insecure".

In general, first understand whether a variable, a method belongs to a class or an object, or a local variable. Then those threads allow sharing and which are not allowed.

Java's thread safety (as I know it) is basically done by synchronizing blocks of code.

1. Thread is not secure

Data between threads is unpredictable, for example, thread a modifies the member variable from 1 to 2, but thread 2 reads a possible 1. (concurrency)

 Public classthreadsecurity { Public Static voidMain (string[] args) {Runnable R1 =NewInsecurity (); Thread T1 =NewThread (R1, "thread-a"); Thread t2 =NewThread (R1, "Thread-b"); Thread t3 =NewThread (R1, "thread-c");        T1.start ();        T2.start ();    T3.start (); }}/** thread is not secure * /classInsecurityImplementsrunnable{Private inti = 5; @Override Public voidRun () {Try{if(i = = 5) {Thread.Sleep (2);//Set a small point to see it I--; System.out.println (Thread.CurrentThread (). GetName () + ": i=5"); }        }Catch(Interruptedexception e)        {E.printstacktrace (); }    }}

The above output results:

Because it is not thread-safe, threads thread-a, Thread-b, and thread-c can be executed: i==5. That is, it is possible for the thread-a to pass the lock to Thread-b if it is finished judging if, and if the thread-b is true at this time. (This illustrates the concurrency between threads, which rotates execution.) Macro view is performed together, because the rotation scheduling time is very short)

2. Thread Safety

/** Thread Safety * / class Implements runnable{    privateint i = 5;    @Override public    void run () {        try {            synchronized  {                if(i = = 5) {                    thread.sleep (2);                    I--;                    System.out.println (Thread.CurrentThread (). GetName () + ": i=5");                }            }        Catch (Interruptedexception e) {            e.printstacktrace ();}}    }

The above demo must only output 1 times.

Vii. blocking, deadlock

Blocking: Thread A gets locked, thread B, and C are waiting. is blocked for thread B, c.

Deadlock: All threads are waiting for other threads to release the lock. (I encountered when writing an Oracle trigger, transaction A is waiting for transaction B to commit, and transaction B is waiting for transaction A to commit.) )

Eight, reference (the following is the original study to organize the blog articles, I did not read carefully, are slowly understand a little)

Java Threading: Concepts and Principles

Java multi-threaded release lock

Java Threading Tutorial-Series

PS: Weekend addicted to the hands of the tour can not extricate themselves, a few want to summarize has not written ... Moreover, I thought this article would write a lot, but look back, still do not know what they wrote. Where did you get so much time to let me take it slow?

The project at hand to blow up, there is no need for investigation and analysis, demand development design, there are 3 core tables are 1 to 1 to 1, now needs to change to 1 to many, 1 to many. And the company's leadership to a sentence of 2-3 days can be changed, I will hehe.

And, moreover, the head of the project was transferred to another project team by the company leader. My Project plus I only 3 people, or 3 new, 2 code 1 operations.

This Wang's heart is not collapsed, long ago by these companies tortured broken, heart good tired ... Good want to return to the countryside, when a proud Chinese pastoral dog!

Thread Java Thread object lock, class lock, thread safety

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.