Java Concurrency (a): Thread the basics as well as the synchronized keyword

1. The concept of the thread of a multithreaded: in a program, the program fragment is capable of independent operation called " thread " (Thread). Multithreading (multithreading) technology refers to concurrent execution of multiple threads from the software or hardware.

2. The significance of multithreading: Multithreading can be quickly switched time slots in cpu, resources can better be called, programming easier in some cases, the program responds faster, run more smoothly.

2. How to start a thread: Thread class inheritance, implement Runnable, implement Callable Interface

3. Why should ensure the synchronization of threads? : Java multithreading allows control, when a plurality of threads operating variables shared resources (e.g., additions and deletions to change search data) will result in inaccurate data, conflict with each other, so as to avoid the synchronization lock was added the thread is not before the operation, to be called from other threads to complete, thus ensuring the uniqueness and the accuracy of the variable.

4. Basic thread synchronization: using synchronized keyword variable domain specific volatile, wait and notify methods.

public  class T {
     Private  int COUNT = 10 ;
     Private Object o = new new Object (); 

    public  void m () {
         the synchronized (o) {
             // any thread to execute the code below, must get o lock 
            count-- ; 
            System.out.println (Thread.currentThread () getName (). + "COUNT =" + COUNT); 
        } 
    } 
}

Suppose this code a plurality of threads, when the first thread to execute the method m, sync locked o the object heap memory, this time is the second thread not come, it must rankings a thread executed, the lock can only be freed then executed. There is a concept called lock mutex , sync is a mutex.

public  class Tl {
     Private  static  int COUNT = 10 ; 

    public  the synchronized  static  void m () {
         // here is equivalent to the synchronized (T3.class) 
        count-- ; 
        . System.out.println (Thread.currentThread () getName () + "COUNT =" + COUNT); 
    } 

    public  static  void mm () {
         the synchronized (Tl. class ) {
             // Consideration: written here synchronized (this) can? 
            count-- ; 
        } 
    } 
}

Thinking here, pay attention to sync is a modified static methods and static properties, static methods and properties are modified do not need a new object can be accessed, so there is not a new subject, sync lock is T3.class object.

public class T2 implements Runnable{
    private int count =10;

    @Override
    public /*synchronized*/ void run(){
        count--;
        System.out.println(Thread.currentThread().getName()+"count="+count);
    }

    public static void main(String[] args) {
        T2 t=new T2();
        for (int i=0;i<5;i++){
            new Thread(t,"THREAD"+i).start();
        }
    }
}

The above code to open the five threads, execute the run method to be minus one count of operating, the problem here thread seize resources occur. When the first thread executes the run method, process and reduction, the second thread also entered the method, also in the same execution and reduction, when the second thread the subtraction may occur before the first thread output count, this time there have been threads reentrant. Processing method can add synchronized keyword, ranking only one thread is finished, the second thread can enter that same time only one thread to operate it, which is the atomicity .

public  class the Account { 

    / ** 
     * account holder and account balances 
     * / 
    String name; 
    Double Balance; 

    / ** 
     * Set the account balance, it is the first thread to sleep for the purpose of reading data 
     * @param name 
     * @param Balance
      * / 
    public  the synchronized  void SET (String name, Double Balance) {
         the this .name = name; 

        the try { 
            the Thread.sleep ( 2000 ); 
        } the catch (InterruptedException E) { 
            e.printStackTrace (); 
        } 
        the this.balance=balance;
    }

    public double getBalance(String name){
        return this.balance;
    }

    public static void main(String[] args) {
        Account a=new Account();
        new Thread(()->a.set("zhangsan",100.0)).start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(a.getBalance("zhangsan"));

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(a.getBalance("zhangsan"));
    }
}

This is a small demo, the code only set method, locking is not locked on the get method, this time there will be dirty read phenomenon. The solution is a method of reading and writing are locked.

public class T3 {

    synchronized void m1(){
        System.out.println("m1 start");
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        m2();
    }

    synchronized void m2() {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("m2");
    }
}

In this case, m1 and m2 plus methods have been locked, when the execution of m1 m2 executed again, this is possible. A synchronization method can invoke another synchronization method, i.e. sync lock is obtained reentrant lock . There is a concept deadlock , deadlock means that multiple threads to seize resources and cause a wait for each other. For example, a box can be opened only need two keys, the keys were in the hands of two people, two men compete with each other another person's key, resulting in open boxes.

Guess you like

Origin www.cnblogs.com/ruiyeclub/p/12288551.html