Home  >  Article  >  Java  >  Detailed explanation of the implementation method of java thread synchronization (with code)

Detailed explanation of the implementation method of java thread synchronization (with code)

不言
不言forward
2018-10-19 16:14:172698browse

This article brings you a detailed explanation of the implementation method of Java thread synchronization (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Why thread synchronization

When we have multiple threads to operate on the same resource, such as files, we cannot allow multiple threads to operate at the same time. to operate this file. Because when files are shared, multiple operations will conflict. I believe that people who have used git for team development will have a profound experience in price comparison.

At this time, the thread synchronization mechanism needs to be introduced.

The so-called synchronization refers to execution one by one, that is, queuing. Several threads are queued for execution, so that there is a first-come, first-served relationship between threads. In this way, there will be no fighting and no conflicts.

Problem description

A program with two threads. The first thread calculates even numbers and numbers between 2 and 1000, and the second thread calculates 1000. Even numbers and numbers between ~2000.

Initial implementation

First of all, we design the implementation method according to the topic.

1. Define two threads. Here you need to define your own thread class, and then set the start and end of calculating even numbers
2. Implement calculation of even numbers and even numbers within the given range
3. Execution thread

You can see The implementation is simple. The preliminary implementation is as follows:

1. Define your own thread class:

public class MyTread extends Thread {
    private int begin;          // 范围开始
    private int end;            // 范围结束

    public MyTread(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }
}

2. Implement calculation of even numbers and even numbers

@Override
public void run() {
    this.getEven(begin, end);
}

// 获取偶数以及个数
private void getEven(int begin, int end) {
    int count = 0;
    System.out.println(begin + "~" + end + "之间的偶数为:");
    if (begin % 2 != 0) {
        begin += 1;
    }

    for (; begin  <p><strong>3. Initialize the thread and run </strong></p><pre class="brush:php;toolbar:false">public static void main(String[] args) {
    MyTread tread1 = new MyTread(2, 500);
    MyTread tread2 = new MyTread(500, 1000);
    tread1.start();
    tread2.start();
}

Note: In order to show the subsequent effect, the number range is reduced.

Look at the results:

Detailed explanation of the implementation method of java thread synchronization (with code)

doesn’t seem to be the effect we want. We want this effect:

Detailed explanation of the implementation method of java thread synchronization (with code)

We want the even and even numbers of each part to be together, but the effect after we implement it is indeed Two parts of confusion arise.

Program improvement

To solve the above problems, we need to use the thread synchronization we talked about at the beginning.

According to our initial introduction, we found that one condition for synchronization is to have a shared resource. So what is this shared resource in our code? It seems not. So create one first.

1. Create shared resources

The shared resources we have here can be the same object, so we will create another class, Used to illustrate shared resources.

public class Even {}

2. Then create a method for calculating even numbers in the shared class:

public class Even {
    /**
     * 获取某个范围内偶数以及个数
     * @param begin 统计开始
     * @param end   统计结束
     */
    public synchronized void getEven(int begin, int end) {
        int count = 0;
        System.out.println(begin + "~" + end + "之间的偶数为:");
        if (begin % 2 != 0) {
            begin += 1;
        }

        for (; begin <p> Careful people will find that this method is a little different from the method we originally wrote. , it has one more keyword: <code>synchronized</code>. Through this keyword, we can achieve thread synchronization when executing methods. </p><p><strong>3. Finally call the shared method in the thread </strong></p><pre class="brush:php;toolbar:false">public class MyTread extends Thread {
    Even even;
    
    @Override
    public void run() {
        even.getEven(begin, end);
    }
}

At this time, let’s execute it again:

Detailed explanation of the implementation method of java thread synchronization (with code)

Achieved the effect we wanted.

Finally, attach the complete code:

/**
 * 偶数类
 */
public class Even {
    /**
     * 获取某个范围内偶数以及个数
     * @param begin 统计开始
     * @param end   统计结束
     */
    public synchronized void getEven(int begin, int end) {
        int count = 0;
        System.out.println(begin + "~" + end + "之间的偶数为:");
        if (begin % 2 != 0) {
            begin += 1;
        }

        for (; begin <p class="comments-box-content"><br></p>

The above is the detailed content of Detailed explanation of the implementation method of java thread synchronization (with code). For more information, please follow other related articles on the PHP Chinese website!

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