java multithreading: thread-safety issues

What is thread safe?

Why is there a thread safety issues?

When multiple threads share the same global variables or static variables when doing a write operation, data conflicts can occur, that is, thread-safety issues. But do not read data conflicts occur.

Rob trains example:

One window and the number two train window while selling the first ninety-nine , part of the ticket sale will be repeated.

Conclusion discovered multiple threads share the same global member variable, do the data write operation may conflict occurs.

 

Second, the thread-safe solution :

Q : How to solve the multi-thread between the thread-safety issues

A : Use the synchronous synchronized between multiple threads or lock (lock).

Q : Why use thread synchronization or thread safety lock can solve the problem?

A : The possible data conflicts (thread safe issue) will happen, only allow a current thread execution. After the completion of the implementation of the code to release the lock, so that after let other threads for execution. In this case we can solve the problem of insecurity thread.

Q : What is synchronization between multiple threads

A : When multiple threads share the same resources, without interference from other threads.

Q : What is a multi-thread synchronization

A : When multiple threads share the same resources, without interference from other threads.

Third, in a synchronized manner

In the method of adding the 1.synchronized, synchronization method 
2.
synchronized code block encases, the synchronization code block

(1) is applied to the method of
synchronized
Package com.bigdata.thread; 

/ ** 
 * @Created IMP by the ON 2019/8/28 
 example * using the grab implement multithreading train safety issues 
 * / 
public  class TicketDemo the implements the Runnable {
     int tickets = 100 ; 


    public   void RUN ( ) {
         the while (tickets> 0 ) {
             the try { 
                the Thread.sleep ( 50 ); 
            } the catch (InterruptedException E) { 
                e.printStackTrace (); 

            } 
            Sale (); 
        } 

    } 

    public  the synchronized void sale() {
        if (tickets > 0) {
            System.out.println(Thread.currentThread().getName() + ",出售 第" + (101 - tickets) + "  票");
            tickets--;
        }
    }


}

class  Main{
    public static void main(String[] args) {
        System.out.println(1);
        TicketDemo  ticketDemo= new TicketDemo();
        Thread t1=new Thread(ticketDemo,"窗口1");
        Thread t2=newThread (ticketDemo, "window 2" ); 
        t1.start (); 
        t2.start (); 
    } 
}
 
Window 2, sell 88 votes 
window 2, the sale of 89 votes 
window 1, the sale of 90 votes 
window 2, sell 91 votes 
window 1, the sale of 92 votes 
window 2, sell 93 votes 
window 1, the sale of 94 tickets 
window 1, ticket sale 95 
window 2, ticket sale 96 
window 1, ticket sale 97 
window 2, ticket sale 98 
window 2, ticket sale 99 
window 1, the sale of votes 100
 

(2) using synchronized code block plus

 
Package com.bigdata.thread; 

/ ** 
 * @Created IMP by the ON 2019/8/28 
 example * using the grab implement multithreading train safety issues 
 * / 
public  class TicketDemo the implements the Runnable {
   Private    int tickets = 100 ;
   Private   Object obj = new new Object (); 

    public   void RUN () {
         the while (tickets> 0 ) {
             the try { 
                the Thread.sleep ( 50 ); 
            } the catch (InterruptedException E) { 
                e.printStackTrace (); 
 
            }
            Sale ();
        }

    }

    public  void sale() {
        synchronized (obj){
            if (tickets > 0) {
                System.out.println(Thread.currentThread().getName() + ",出售 第" + (101 - tickets) + "  票");
                tickets--;
            }
        }

    }


}

class  Main{
    public static void main(String[] args) {
        System.out.println(1);
        TicketDemo  ticketDemo= new TicketDemo();
        Thread t1=new Thread(ticketDemo,"窗口1");
        Thread t2=new Thread(ticketDemo,"窗口2");
        t1.start();
        t2.start();
    }
}
 

3. If the object is how to synchronize two threads

Because the two new objects, if the tickets (ticket number), obj (lock object code block) is static, they are in the process area can be shared, synchronization

If it is not static, that is, property, lock the votes of two objects are not the same and can not be synchronized

A: What is a static synchronous functions?

Plus the method static keyword, use the synchronized keyword or use modified class .class file.

Static lock synchronization function uses  the function belongs bytecode file object

You can use getClass acquisition method, you can also use the current class name .class representation.

Package com.bigdata.thread; 

/ ** 
 * @Created IMP by the ON 2019/8/28 
 example * using the grab implement multithreading train safety issues 
 * / 
public  class TicketDemo the implements the Runnable {
   Private   static  int tickets = 100 ;
   Private  static obj = Object new new Object (); 

    public   void RUN () {
         the while (tickets> 0 ) {
             the try { 
                the Thread.sleep ( 50 ); 
            } the catch (InterruptedException E) { 
                e.printStackTrace ();

            }
            sale();
        }

    }

    public  void sale() {
        synchronized (obj){
            if (tickets > 0) {
                System.out.println(Thread.currentThread().getName() + ",出售 第" + (101 - tickets) + "  票");
                tickets--;
            }
        }

    }


}

class  Main{
    public static void main(String[] args) {
        System.out.println(1);
        TicketDemo  ticketDemo1= new TicketDemo();
        TicketDemo  ticketDemo2= new TicketDemo();
        Thread t1=new Thread(ticketDemo1,"窗口1");
        Thread t2=new Thread(ticketDemo2,"窗口2");
        t1.start();
        t2.start();
    }
}

4. Static synchronization method: static synchronized void sale () corresponds, the synchronized (current class .class), byte code lock,

    public  void sale() {
        synchronized (TicketDemo.class){
        if (tickets > 0) {
            System.out.println(Thread.currentThread().getName() + ",出售 第" + (101 - tickets) + "  票");
            tickets--;
        }
    }

    }
    public static synchronized void sale() {
            if (tickets > 0) {
                System.out.println(Thread.currentThread().getName() + ",出售 第" + (101 - tickets) + "  票");
                tickets--;
            }


    }

to sum up:

Synchronized (this)
lock the target code block, and other threads to access the object executed, other threads can execute.
Synchronized (xxx.class)
 to lock the class, all threads access the class, only one can be executed.
Other
A. Whether the synchronized keyword added to the method or an object, if the object is non-static effect it, lock it made object; if the object is synchronized action of a static method or a class, lock it made is a class, all objects in the same lock.
B. Each object is only associated with a lock (lock) with them, who got this lock and anyone can run that code it controls.
C. synchronized to a lot of overhead expense, and may even cause a deadlock, so try to avoid unnecessary synchronization control

Fourth, multi-threaded deadlock

 What is multi-threaded deadlock?

 

   A : Synchronization nested sync , leading to the lock can not be released

五、Threadlocal

What is Threadlocal

ThreadLocal improve the local variables of a thread, a thread to access its own local variables.

 When using ThreadLocal maintenance variables, ThreadLocal provide a thread for each use of the variable copy of the independent variables, so each thread can independently change their copy without affecting other threads corresponding copy.

ThreadLocal interface methods

ThreadLocal class interface is very simple, only 4 Ge method, we first take a look:

• void set (Object value) value of the current thread's thread local variables.

• public Object get () method returns the current thread corresponding to the thread-local variables.

• public void remove () the value of the local variables of the current thread deleted, the purpose is to reduce memory usage, which is JDK 5.0 new method. 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.

• protected Object initialValue () 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, in the first thread 1 call times get () or set (Object) when execution, and perform only 1 times. ThreadLocal default of a direct return null .

My understanding is equivalent to broadcast variables, will broadcast the public variables to each thread, each thread separately to operate the variable

CHARACTERISTICS OF SIX, multithreading

Multithreading has three major characteristics

Atomicity , visibility , order of

What is atomicity

I.e., a plurality of operation or operations either all performed and the process will not be interrupted to perform any factor, or it is not performed.

A classic example is the bank account transfer problem:
for example, from the account transfer A to account B 1000 yuan, it must include two actions: A minus 1000 yuan from the account, to account B plus 1,000 yuan. These two operations must have the atomicity to ensure that there is some unexpected problems.

We also true operational data, such as i = i + 1; including the read value of i, i is calculated, written i. This line of code in Java is not available atomic, then there will be problems running multi-threaded, so we also need to use synchronization and lock these things to make sure that this feature of.

In fact, atomicity is to ensure data consistency, security thread part,

What is the visibility

When multiple threads access the same variable, a thread changes the value of this variable, other threads can immediately see the modified values.

If two threads in different cpu, then thread 1 changes the value of i did not modify the thread to refresh main memory, thread 2 and i use, it is still before the affirmation of the value of i, the thread 1 of the variables did not see this is the visibility of the problem.

What is orderly

The program execution sequence performed in the order code.

In general processor in order to improve process efficiency, might enter the code optimization, it does not ensure the implementation of the program in individual statements in the order consistent with the order of the code, but it will ensure that the final program execution and results of the code sequence the result is the same. as follows:

int a = 10; // statement 1

int r = 2; // statement 2

a = a + 3; // statement 3

r = a * a; // statement 4

Because the reordering, he might order of execution is 2-1-3-4,1-3-2-4
but not likely 2-1-4-3, because it breaks the dependency.
Obviously reorder single thread is not going to have any problems, but not necessarily multi-threaded, so we have to consider this issue at the time of multi-threaded programming.

 

 

Guess you like

Origin www.cnblogs.com/hejunhong/p/11427234.html