A brief understanding of the difference between processes and threads in the operating system:
Process: Each process has independent code and data space (process context), and switching between processes will have a large overhead. A process contains 1-n threads. (Process is the smallest unit of resource allocation)
Thread: The same type of threads share code and data space. Each thread has an independent running stack and program counter (PC), and the thread switching overhead is small. (Thread is the smallest unit of CPU scheduling)
Like a process, threads are divided into five stages: creation, ready, running, blocking, and terminating.
Multi-process means that the operating system can run multiple tasks (programs) at the same time.
Multithreading refers to multiple sequential streams being executed in the same program. First of all, the operation of saving money and withdrawing money should be threaded, and there can be many customers. This means that there must be multiple threads, and multiple threads jointly operate a bank, and the amount of the bank needs to be synchronized. Only by ensuring thread safety.
So, let’s put this example of this code here. If there is something wrong, please point it out. Because an old man asked about this multi-threaded code.
First of all, the bank, the creation of this object model.
package com.lxk.threadTest.bank;/** * Bank model, a total amount attribute. * <p> * * @author lxk on 2017/6/26 */public class Bank {/** * Give the bank a start-up capital, otherwise how can you do business. */private int sum = 200;//This is never used like this, but it is also a correct locking mechanism: synchronize code blocks. //Object obj = new Object(); /** * Save money* If you do not add [synchronized--sync function], multi-threaded safety problems will occur. */public synchronized void add(int n) {//synchronized (obj) { sum = sum + n;try {Thread.sleep(10);}catch (Exception ignore) {}//When the number of times of saving money becomes more, you can find that the saving money threads are indeed two alternately performing the saving action. System.out.println(Thread.currentThread().getName() + "...sum=" + sum);//}}/** * Withdraw money* If you do not add [synchronized--sync function], multithread safety problems will occur. */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 the number of times of saving money becomes more, you can find that the threads that save money are indeed two alternately performing the action of saving money. System.out.println(Thread.currentThread().getName() + "...sum=" + sum);}}There are two methods in the code: Save and fetch, these two methods, and a total amount, and some commented out code. That is simple and easy to understand, multi-threaded locking mutually exclusive, and ensures synchronization between threads.
However, this is an infrequent method. The commonly used method is to use the synchronized keyword to modify the synchronization method.
Model of client object
package com.lxk.threadTest.bank;/** * Customer, implement the runnable() interface, and multiple people can save money together* * @author lxk on 2017/6/26 */public class Customer implements Runnable {/** * Saving type*/static final String TYPE_ADD = "add";/** * withdrawal type*/static final String TYPE_REDUCE = "reduce";/** * Bank*/private Bank bank;/** * Operation type for money, saving or withdrawal */private String type;/** * The number of operations is theoretically a positive number*/private int time;/** * How much to save 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);}}}}As a customer object, since many customers can access a bank at the same time, the operation of saving and withdrawing money is implemented using threads.
The attribute is constructed to pass the value.
Main method
package com.lxk.threadTest.bank;/** * Multi-threaded instance of bank depositing money* <p> * [Requirements:] * The bank has a vault. * There are two depositors who deposit or withdraw n * 100 respectively. * Purpose: Is there any security problem with this program? If so, how to solve it? * <p> * [How to find the problem:] * 1. Clear which codes are multi-threaded codes. * 2. Clearly share data. * 3. Clear which statements in multi-threaded 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 effect of the above code is shown in the figure below.
If the number of times of deposit and withdrawal of money is small, you may see that the two threads have a sequence. Therefore, we have a larger number of times. Then, we will see the situation as shown in the figure. Thread 1 withdraws money, and when thread 0 saves money, you can see that the two threads are executed interleaved, with both storage and withdrawal, and there is no pattern.
This ensures data synchronization.
As for how to be out of synchronization, that is, abnormal phenomena,
You can remove the synchronized keyword of the add method, reduce the number of times and change it to 3 times, and set the initial value of sum to 0. Try the code again,
You will find the so-called async phenomenon.
The result of the out-of-synchronization on the right side of the figure above is that the two people save 100 each time, three times. Is the total number obtained? 100,200,300,400,500,600. It takes a long time.
However, the operation result is not
At this time, if you add synchronized to the add method, the result of the graph on the left will appear, which is the correct result.
I added another method for the sake of existence and withdrawal. The code becomes what it looks like above.
These are almost all examples of inter-thread synchronization.
I will record the code briefly. When used, you can take it out in minutes.
Summarize
The above is the complete code of this article on simulating Java multithreaded synchronization problem using bank withdrawal as an example. I hope it will be helpful to everyone. Interested friends can continue to refer to this site:
Java multithreaded programming example
The principle and implementation of Java multithreaded timer Timer
Java understands multi-threading by selling tickets
If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!