In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the example analysis of Java multi-thread synchronization, which is very detailed and has certain reference value. Friends who are interested must finish it!
Briefly understand the difference between processes and threads in the operating system:
Process: each process has its own code and data space (process context), switching between processes will have a large overhead, a process contains 1 Murray n threads. (process is the smallest unit of resource allocation)
Threads: the same kind of threads share code and data space, and each thread has its own running stack and program counter (PC), so the thread switching overhead is small. (thread is the smallest unit of cpu scheduling)
A thread, like a process, is divided into five phases: create, ready, run, block, and terminate.
Multiprocess means that the operating system can run multiple tasks (programs) at the same time.
Multithreading means that there are multiple sequential streams executing in the same program. First of all, the operation of saving and withdrawing money should be thread-operated, and there can be a lot of customers, which means that there have to be multiple threads, multiple threads operate a bank together, and the amount of the bank needs to be synchronized. To ensure thread safety.
So, let's put an example of this code here. If there is something wrong, please point it out. Because an old friend asked this multi-threaded code.
The first is the bank, the creation of this object model.
Package com.lxk.threadTest.bank;/** * Bank model, a total amount attribute. *
* * @ author lxk on 2017-6-26 * / public class Bank {/ * give the bank start-up capital, otherwise how to do business. * / private int sum = 200; / / this is never used in this way, but it is the right locking mechanism: synchronizing code blocks. / / Object obj = new Object (); / * * Save * if you don't add [synchronized-- synchronization function], there will be multi-thread safety problems. * / public synchronized void add (int n) {/ / synchronized (obj) {sum = sum + n; try {Thread.sleep (10) } catch (Exception ignore) {} / / when you save more times, you can find that there are indeed two threads that save money alternately. System.out.println (Thread.currentThread (). GetName () + ".. sum =" + sum); / /}} / * * withdraw money * if you don't add [synchronized-- synchronization function], there will be multi-thread safety problems. * / public synchronized void reduce (int n) {if (sum-n > = 0) {sum = sum-n;} else {System.out.println ("bank's money is not enough!");} try {Thread.sleep (30) } catch (Exception ignore) {} / / when you save more times, you can find that there are indeed two threads that save money alternately. System.out.println (Thread.currentThread (). GetName () + ".. sum =" + sum);}}
There are two methods of saving and fetching in the code, these two methods, and a total amount, in which there is a part of the commented-out code, which is easy to understand, multi-thread lock mutual exclusion, to ensure synchronization between threads.
But this is not a common method, it is commonly used to use the keyword synchronized to modify the synchronization method.
Model of the customer object
Package com.lxk.threadTest.bank;/** * customers, implement the runnable () interface. Multiple individuals can deposit money together * * @ author lxk on 2017-6-26 * / public class Customer implements Runnable {/ * savings type * / static final String TYPE_ADD = "add"; / * withdrawal type * / static final String TYPE_REDUCE = "reduce" / * Bank * / private Bank bank; / * the type of operation for money, the number of times or withdraws money * / private String type; / * * is theoretically a positive number * / private int time; / * how much money to deposit or withdraw * / private int money Public Customer () {} public Customer (Bank bank, String type, int time, int money) {this.bank = bank; this.type = type; this.time = time; this.money = money;} @ Override public void run () {for (int x = 0) X < time; x +) {if (TYPE_ADD.equals (type)) {bank.add (money);} else if (TYPE_REDUCE.equals (type)) {bank.reduce (money) }}
Customer object, because many customers can access a bank at the same time, so the operation of saving and withdrawing money is realized by thread.
Property is passed by the constructor.
Main method
Package com.lxk.threadTest.bank;/** * multithreaded instance of bank deposit *
* [demand:] * the bank has a vault. * two depositors deposit or withdraw n * 100 respectively. * purpose: is there any security problem in the program, and if so, how to solve it? *
* [how to find the problem:] * 1, make it clear which code is multithreaded. * 2, explicitly share data. * 3 to identify which statements in the multithreaded running code operate on shared data. * * @ author lxk on 2017-6-26 * / public class Main {public static void main (String [] args) {/ / one bank and multiple customers Bank bank = new Bank (); int time = 10000; int money = 100 / / this customer saves money Customer C1 = new Customer (bank, Customer.TYPE_ADD, time, money); / / this customer withdraws money Customer c2 = new Customer (bank, Customer.TYPE_REDUCE, time, money); Thread T1 = new Thread (C1); Thread T2 = new Thread (c2) T1.start (); t2.start ();}}
The actual operation of the above code is shown in the following figure.
If the number of times to deposit and withdraw money is small, you may see that the two threads are in sequence, so let's make more of this number, and then, as shown in the figure, thread 1 withdraws money, and thread 0 saves money. You can see that the two threads are staggered with each other, there are storage and fetch, there are no rules to speak of.
This ensures the synchronization of the data.
As for how to be out of sync, that is, an abnormal phenomenon.
You can remove the synchronized keyword of the add method, change the number of times to 3 times, and set the initial value of sum to 0. 0. You try the code again.
You will find the so-called out-of-sync phenomenon.
The right side of the picture above is the result of being out of sync. Two people save 100 at a time, three times, and the total is 100200300400500600. Long.
However, the result of the operation is not
At this point, if you add synchronized to the add method, the result of the diagram on the left will appear, which is the correct result.
I did it for the sake of deposit and withdrawal, so I added another method. The code will look like the above.
Almost all examples of synchronization between threads.
The above is all the contents of the article "sample Analysis of Java Multithreading synchronization problems". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.