Home  >  Article  >  Java  >  Java thread safety and synchronization example analysis

Java thread safety and synchronization example analysis

WBOY
WBOYforward
2023-04-29 20:58:05800browse

Thread safety issues

Multiple threads may share (access) the same resource

For example, access the same object, the same variable, the same file

When When multiple threads access the same resource, it is easy to cause data confusion and data security issues, which are called thread safety issues

Under what circumstances will thread safety issues occur

Multiple threads share the same Resource

And at least one thread is performing the write operation

Example:

Deposit and withdrawal problems

There are 2 deposits and withdrawals respectively Threads

Deposit money Withdraw money
Thread 1 Balance Thread 2
1000 "----1000------" 1000
1000 1000---- -》2000
            500 "-----1000-500

Correct: the balance after the end should be 1500, not 500

Ticket purchase problem

2 threads


# thread 1 ticket number thread 2
1000 "---- 1000 ------" 1000
# 1000-1-----》999
        999 "-----1000-1

Correct: the balance after the end should be 998, not 999

Ticket purchase error (not thread synchronized) example:

public class love implements Runnable{
    private int piao=3000;//有3000张票
    public boolean sale() {//ture代表还有票;false代表没有票了
        if(piao<1) return false;
         piao--;//卖1张票
         
         //细化piao--;
         //寄存器=piao;
         //寄存器=寄存器-1;
         //piao=寄存器;
         
         String sk =Thread.currentThread().getName();//获取当前线程(买票窗口)的名字
         System.out.println(sk+"卖了1张票,还剩下"+piao+"张");
         return piao>1;
    }
    public void run() {
         while(sale());//循环执行;直至卖完票返回false
    }
}
 
public class Main {
    public static void main(String[] a) {
        love tjlove =new love();
        for(int i=1;i<=4;i++) {//循环4次;产生4个线程(窗口)卖票
            Thread tj = new Thread(tjlove());
            tj.setName(""+i);
            tj.start();
        }
    }
}

Partial output result:

Java thread safety and synchronization example analysis

##Thread safety issue

Analysis issue
Threads A and B perform 1 operation on 1 variable in the class with a value of 17

The final result is 2 18

Solution
Lock:

Process: First, thread A accesses this 17 first. After reading it, it locks and enters 1. The operation is changed to 18

and 17 cannot be accessed by other threads during the locking period.
After the change, write Enter, and then unlock 17
Then thread B accesses it, locks it, repeats the above operation to become 19 and then unlocks it
This can ensure that only one thread accesses it at the same time, so Security is guaranteed; the previous error was due to these threads accessing it together

Thread synchronization

The locking operation just mentioned is thread synchronization technology

can be used Thread synchronization technology to solve thread safety issues

Thread synchronization has two methods in Java:

1. Synchronization statement

2. Synchronization method

Synchronization statement

public class love implements Runnable{
	private int piao=3000;//本人cpu单核性能过强,数据量大些才能看到是4个线程在卖票
	public boolean sale() {
		synchronized(this) {//1个线程获取这个对象的锁,并加锁;    synchronized作用于整个语句
		//this指向当前对象
		//不能用new Object();这样会产生新的对象,产生新的锁
		//把this换成"123",效果基本一样;因为其存在常量值里,每次访问的对象一样
			if(piao<1) return false;
			piao--;
			String sk =Thread.currentThread().getName();
			System.out.println(sk+"卖了1张票,还剩下"+piao+"张");
			return piao>0;
			}
	}
	public void run() {
		 while(sale());
	}
}

Partial output result:

Java thread safety and synchronization example analysis

Principle of synchronize(obj)

1. Each object has an associated The related intrinsic lock (intrinsic lock) or monitor lock (monitor lock)

2. The first thread that executes the synchronization statement can obtain the internal lock of obj. After executing the code in the synchronization statement Release this lock

3. As long as one thread holds the internal lock, other threads will no longer be able to obtain this lock at the same time

✓ When they try to obtain this lock, they will enter BLOCKED state

4. When multiple threads access the same synchronized(obj) statement

obj must be the same object to achieve synchronization

Synchronization method

public class love implements Runnable{
    private int piao=3000;
    public synchronized boolean sale() { //synchronized作用于整个方法
            if(piao<1) return false;
            piao--;
            String sk =Thread.currentThread().getName();
            System.out.println(sk+"卖了1张票,还剩下"+piao+"张");
            return piao>0;
    }
    public void run() {
         while(sale());
    }
}

synchronized cannot modify the constructor

The essence of synchronized methods
Instance method: synchronized (this)

Static method: synchronized (Class object)

Synchronization statements are more flexible than synchronization methods

Synchronization statements can accurately control the code range that needs to be locked, reduce the number of threads in the BLOCKED state, and make full use of labor

Use thread synchronization After the technology

Although it solves the thread safety problem, it reduces the execution efficiency of the program

Because if a lock is added, there will be waiting threads, and there are more lock and unlock operations

So only use thread synchronization technology when it is really necessary

The above is the detailed content of Java thread safety and synchronization example analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete