Dark Horse programmer ———— Java multithreading and synchronization mechanism

Source: Internet
Author: User

------<a href= "http://www.itheima.com" target= "blank" >java training, Android training, iOS training,. NET training </a>, look forward to communicating with you! -------

  

1. Understanding the concepts of programs, processes, threads
The program can be understood as static code, a collection of computer instructions, which are stored on disk as files.
A process can be understood as an executing program, and a separate program opens a separate piece of address space for individual work.
Threads can be understood as a further subdivision of a process, an execution path of the program.

Multithreading does not mean that many threads run at the same time, but rather a fast switchover of the CPU.

The thread is roughly divided into five states:

Create through new thread and its subclasses

Running the executing thread, occupying the CPU

Blocking has the executive qualification, just not grabbing the CPU, which is randomly CPU-determined

Freeze no-execute eligibility, in hibernation

The extinction Run method finishes executing (1.5 can force the end thread by calling the Stop method before)

The thread is essentially created by Windows, and Java has encapsulated the thread that created it, just to use it, and inherit the thread class from the Java.lang package. Broadly divided into two ways

Method One: Inherit the thread class directly

Class Printnum extends thread{//inherits the thread class public void run () {///replication Run method, the code that the child thread executes for (int i = 1;i <= 100;i++) {if (i% 2 = = 0) {System.out.println (Thread.CurrentThread (). GetName () + ":" + i);}}} Public Printnum (String name) {super (name);}} public class Testthread {public static void main (string[] args) {printnum P1 = new Printnum ("Thread 1"); Printnum P2 = new Printnum ("Thread 2");p 1.setPriority (thread.max_priority);//Priority 10p2.setpriority (thread.min_priority); /priority 1p1.start ();//start thread and call the Run Method P2.start ();}}

It is divided into three steps: 1. Create thread 2. The Run method in the replication tread, that is, the code block to be executed 3. Call the Stat method, start the thread, and call the Run method

Method Two: Implement Runnable interface

Class Subthread implements Runnable{public void Run () {//2. Replication Run method//child thread Execution code for (int i = 1;i <= 100;i++) {if (i% 2 = = 0) {S Ystem.out.println (Thread.CurrentThread (). GetName () + ":" + i);}}} public class Testthread{public static void Main (string[] args) {subthread s = new Subthread (); thread T1 = new Thread (s),//1. Thread thread t2 = new Thread (s), T1.setname ("Thread 1"), T2.setname ("Thread 2"); T1.start ();//3. Start and call the Run Method T2.start ();}}

  

Comparison of the two methods:

If the class does not inherit other classes, the Run method is written in the thread class, and the multiple loop bodies that appear in a large piece of code are wrapped in an anonymous inner class to enable multithreading to be more concise.

New Thread () {public     void run () {for          (int i=0;i<100;i++) {               System.out.println (i);          }        }}  . Start ();

However, single inheritance has limitations, and if multiple threads have shared data, it is recommended to use implementations, while the class where the shared data resides can be used as an implementation class for the Runnable interface, and the Run method is written in the Runnable interface. For example, two windows buy 100 tickets at a time.

Class Gxzy implements RUNNABLE{//implementation Runnable interface private int piao=100;public void run () {//Override Run method while (true) {if (piao>0 ) System.out.println (Thread.CurrentThread (). GetName () + "  +piao--+" ticket);}} public class Maipiao {public static void main (string[] args) {Gxzy GX = new Gxzy (); Thread XZ1 =new thread (GX);//create thread thread xz2 =new thread (GX), Xz1.setname ("1th ticket Window"), Xz2.setname ("2nd ticket Window"); Xz1.start ( );//start thread and call the Run Method Xz2.start ();}}

However, there is a security problem with the above program, that is, if the thread is running under the IF statement, the CPU is accounted for by other programs (the program OH), then the threads are in a blocking state, and the other threads are in the back, and when the thread returns to the running state, the last ticket is just sold. It is possible that the following thread will sell the No. 0 ticket and write a sleep method to clearly see where the problem is.

Class Gxzy implements runnable{private int Piao=100;object obj = new Object ();p ublic void Run () {while (true) {if (piao>0) Try{thread.sleep (3);//Stop 3 milliseconds}catch (Exception e) {}system.out.println (Thread.CurrentThread (). GetName () + "  No." + piao--+ "Ticket");}}}

At this point, you need to use synchronization to solve the synchronization, provide a lock, when the thread executes the Run method, the lock is closed, the other threads are unable to go in, until the thread completes the lock open, other threads can come in.

Synchronized keyword for synchronization, there are two ways to write out the synchronization code block, the lock can be any object, generally use the object class or the existing resource class

Synchronized (object) {code block executed}

There is also a synchronized modifier on a function called a synchronization function, that is, the code block that you want to synchronize to write in a method, and then use the synchronized decoration. The lock here is this, if the function is modified by static, because the static cannot have this also before the object exists so his lock is the Java.class bytecode file object, in the format class name. class.

Whether you are synchronizing code blocks or synchronizing code functions, there are two prerequisites for use, with two or more threads, and multiple threads using the same lock.

 

Look at the lazy type in singleton mode and solve his threading problem with synchronization

class aa{private static AA BB =null;private aa () {}public static AA lei () {if (bb==null);//double-judging, improved efficiency synchronized (AA.CLASS) {///After the object is created, access to all threads is rejected if (bb==null) {bb=new aa ();} return BB;}}}

We do not use the synchronous function instead of the code block, this is more flexible, if the direct use of synchronous function, will be very inefficient, even when the object is created will be constantly wired access to the lock, and a major drawback of the lock is very expensive resources. In the case of a code block using double judgment, a decision is made in front of the lock, and no further access to the lock is required. It's also worth noting that functions that return objects are static, while static locks are class names. class.

Dark Horse programmer ———— Java multithreading and synchronization mechanism

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.