Home>Article>Java> Detailed explanation of Java thread synchronization and synchronization methods

Detailed explanation of Java thread synchronization and synchronization methods

Y2J
Y2J Original
2017-05-04 09:59:31 1635browse

This article mainly introduces Java threads through examples: thread synchronization-synchronization method. Friends in need can refer to it

Thread synchronization is to ensure multi-threadedsecurityaccess to competitive resources the wrist of.

Thread synchronization is the difficulty of Java multi-threadingProgramming. Developers often don’t understand what competing resources are, when synchronization needs to be considered, how to synchronize, etc. Of course, these problems There is no clear answer, but there are some principle issues that need to be considered. Are there competing resources being modified at the same time?

For synchronization, the following two operations need to be completed in the specific Java code:

Mark the resource competing for access as private;

Synchronize the code that modifiesvariables, use the synchronized keyword to synchronize methods or codes.

Of course this is not the only way to control concurrency security.

Instructions for using the synchronized keyword

synchronized can only mark non-abstract methods and cannot identify member variables.

In order to demonstrate the use of the synchronization method, a credit card account was constructed with an initial credit limit of 1 million, and then multiple operations such as overdraft and deposit were simulated. Obviously the bank account Userobjectis a competing resource, and the account method oper(int x) is used for multiple concurrent operations. Of course, synchronization should be added to this method, and the account balance should be set as a private variable.

Direct access is prohibited.

/** * Java线程:线程的同步 * * @author leizhimin 2009-11-4 11:23:32 */ public class Test { public static void main(String[] args) { User u = new User("张三", 100); MyThread t1 = new MyThread("线程A", u, 20); MyThread t2 = new MyThread("线程B", u, -60); MyThread t3 = new MyThread("线程C", u, -80); MyThread t4 = new MyThread("线程D", u, -30); MyThread t5 = new MyThread("线程E", u, 32); MyThread t6 = new MyThread("线程F", u, 21); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); t6.start(); } } class MyThread extends Thread { private User u; private int y = 0; MyThread(String name, User u, int y) { super(name); this.u = u; this.y = y; } public void run() { u.oper(y); } } class User { private String code; private int cash; User(String code, int cash) { this.code = code; this.cash = cash; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } /** * 业务方法 * @param x 添加x万元 */ public synchronized void oper(int x) { try { Thread.sleep(10L); this.cash += x; System.out.println(Thread.currentThread().getName() + "运行结束,增加“" + x + "”,当前用户账户余额为:" + cash); Thread.sleep(10L); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public String toString() { return "User{" + "code='" + code + '\'' + ", cash=" + cash + '}'; } }

Output result:

线程A运行结束,增加“20”,当前用户账户余额为:120 线程F运行结束,增加“21”,当前用户账户余额为:141 线程E运行结束,增加“32”,当前用户账户余额为:173 线程C运行结束,增加“-80”,当前用户账户余额为:93 线程B运行结束,增加“-60”,当前用户账户余额为:33 线程D运行结束,增加“-30”,当前用户账户余额为:3

Negative teaching material, out of synchronization situation, that is, remove the synchronized modifier of the oper(int x) method, and then run program, the result is as follows:

线程A运行结束,增加“20”,当前用户账户余额为:61 线程D运行结束,增加“-30”,当前用户账户余额为:63 线程B运行结束,增加“-60”,当前用户账户余额为:3 线程F运行结束,增加“21”,当前用户账户余额为:61 线程E运行结束,增加“32”,当前用户账户余额为:93 线程C运行结束,增加“-80”,当前用户账户余额为:61

Obviously, the above result is wrong. The reason for the error is that multiple threads concurrently access the competing resource u, and modify u'sattributeChanges were made.

Visible the importance of synchronization.

Note:

As can be seen from the above, when the threadexits thesynchronization method, the lock of the object to which the method belongs will be released. But it should also be noted that specific methods can also be used to schedule threads in synchronization methods. These methods come from the java.lang.Object class.

void notify() 唤醒在此对象监视器上等待的单个线程。 void notifyAll() 唤醒在此对象监视器上等待的所有线程。 void wait() 导致当前的线程等待,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法。 void wait(long timeout) 导致当前的线程等待,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者超过指定的时间量。 void wait(long timeout, int nanos) 导致当前的线程等待,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者其他某个线程中断当前线程,或者已超过某个实际时间量

Combining the above methods, it is very important to deal with multi-thread synchronization and mutual exclusion issues. The famous producer-consumer example is a classic example that must be learned for multi-threading in any language.

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn