Home > Java > javaTutorial > Detailed tutorial on the thread memory model in Java

Detailed tutorial on the thread memory model in Java

零下一度
Release: 2017-05-25 16:14:54
Original
1030 people have browsed it


java thread memory model

All threads share the main memory, each thread has its own working memory

refreshing local memory to/from main memory must comply to JMM rules
Copy after login

The reasons for thread safety

The thread's working memory is an abstract description of the CPU's registers and cache: In today's computers, when the CPU is calculating, it does not always draw data from the memory. Read data, its data reading order priority is: Register-Cache-Memory. Threads consume CPU. When threads calculate, the original data comes from memory. During the calculation process, some data may be read frequently. These data are stored in registers and caches. After the threads complete calculations, these cached data Data should be written back to memory when appropriate. When multiple threads read and write certain memory data at the same time, multi-thread concurrency problems will occur, involving three characteristics: atomicity, orderliness, and visibility. Platforms that support multi-threading will face this problem, and languages ​​that support multi-threading running on multi-threaded platforms should provide solutions to this problem.

JVM is a virtual computer. It will also face multi-thread concurrency problems. Java programs run on the Java virtual machine platform. It is impossible for Java programmers to directly control the interaction between underlying threads and register cache memory. Synchronization, then Java should provide developers with a solution from the syntax level. This solution is such as synchronized, volatile, lock mechanism (such as synchronized block, ready queue, blocking queue) and so on. These solutions are only at the grammatical level, but we need to understand them in essence;

Each thread has its own execution space (i.e. working memory). When a thread uses a variable during execution, the variable must first be Copy your own working memory space from the main memory, and then operate the variables: reading, modifying, assigning values, etc., all of which are completed in the working memory. After the operation is completed, the variables are written back to the main memory;

Each Threads all obtain data from main memory, and the data between threads is invisible; for example: the original value of main memory variable A is 1, thread 1 takes out variable A from main memory, modifies the value of A to 2, and in thread 1 When variable A is not written back to the main memory, the value of variable A obtained by thread 2 is still 1;

This leads to the concept of "visibility": when a shared variable is in the working memory of multiple threads When there are copies in the shared variable, if one thread modifies the copy value of the shared variable, other threads should be able to see the modified value. This is a multi-thread visibility problem.

Ordinary variable situation: For example, thread A modifies the value of an ordinary variable and then writes it back to the main memory. Another thread B reads from the main memory after thread A completes the write-back operation. Only the value of the new variable will be visible to thread B;

How to ensure thread safety

Writing thread-safe code is essentially to manage the state(state) access, and usually shared, mutable state. The status here is the variables of object (staticvariables and instance variables)

The premise of thread safety is whether the variable is accessed by multiple threads, ensuring that the thread of the object Security requires the use of synchronization to coordinate access to its mutable state; failure to do so can lead to dirty data and other unpredictable consequences. Whenever more than one thread accesses a given state variable and one of the threads writes to the variable, synchronization must be used to coordinate the threads' access to the variable. The primary synchronization mechanism in Java is the synchronized keyword, which provides exclusive locks. In addition to this, the term "synchronization" also includes the use of volatile variables, explicit locks and atomic variables.

Without correct synchronization, if multiple threads access the same variable, your program may be at risk. There are 3 ways to fix it:

l Don't share variables across threads;

l Make state variables immutable; or

l Make state variables any time you access them Use sync.

Volatile requires that every modification of a variable by the program be written back to the main memory. This solves the visibility problem for other thread courseware, but cannot guarantee the consistency of the data; special attention: atomic operations: According to the Java specification, assignment or return value operations to basic types are atomic operations. But the basic data types here do not include long and double, because the basic storage unit seen by the JVM is 32 bits, and both long and double are represented by 64 bits. Therefore, it cannot be completed in one clock cycle

In layman's terms, the state of an object is its data, which is stored in state variables, such as instance fields or static fields; no matter when, as long as more than one thread accesses given state variables. And one of the threads will write to the variable. At this time, synchronization must be used to coordinate the thread's access to the variable;

Synchronization lock: Each JAVA object has and only one synchronization lock. At any time, At most one thread is allowed to own this lock.

当一个线程试图访问带有synchronized(this)标记的代码块时,必须获得 this关键字引用的对象的锁,在以下的两种情况下,本线程有着不同的命运。

1、 假如这个锁已经被其它的线程占用,JVM就会把这个线程放到本对象的锁池中。本线程进入阻塞状态。锁池中可能有很多的线程,等到其他的线程释放了锁,JVM就会从锁池中随机取出一个线程,使这个线程拥有锁,并且转到就绪状态。

2、 假如这个锁没有被其他线程占用,本线程会获得这把锁,开始执行同步代码块。

(一般情况下在执行同步代码块时不会释放同步锁,但也有特殊情况会释放对象锁

如在执行同步代码块时,遇到异常而导致线程终止,锁会被释放;在执行代码块时,执行了锁所属对象的wait()方法,这个线程会释放对象锁,进入对象的等待池中)

Synchronized关键字保证了数据读写一致和可见性等问题,但是他是一种阻塞的线程控制方法,在关键字使用期间,所有其他线程不能使用此变量,这就引出了一种叫做非阻塞同步的控制线程安全的需求;

ThreadLocal 解析

顾名思义它是local variable(线程局部变量)。它的功用非常简单,就是为每一个使用该变量的线程都提供一个变量值的副本,是每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突。从线程的角度看,就好像每一个线程都完全拥有该变量。

每个线程都保持对其线程局部变量副本的隐式引用,只要线程是活动的并且 ThreadLocal 实例是可访问的;在线程消失之后,其线程局部实例的所有副本都会被垃圾回收(除非存在对这些副本的其他引用)。

Object wait()和notify()方法解析

Object的wait()和notify()、notifyAll()方法,使用一个对象作为锁,然后调用wait()就会挂起当前线程,同时释放对象锁;

notify()使用要首先获取对象锁,然后才能唤醒被挂起的线程(因为等待对象锁而挂起的)

notifyAll():唤醒在此对象监视器上等待的所有线程。

wait()在其他线程调用此对象的 notify() 方法或 notifyAll() 方法前,导致当前线程等待。

抛出: IllegalMonitorStateException - 如果当前线程不是此对象监视器的所有者

package com.taobao.concurrency;
public class WaitTest {
    public static String a = "";// 作为监视器对象

    public static void main(String[] args) throws InterruptedException {
        WaitTest wa = new WaitTest();
        TestTask task = wa.new TestTask();
        Thread t = new Thread(task);
        t.start();
        Thread.sleep(12000);
        for (int i = 5; i > 0; i--) {
            System.out.println("快唤醒挂起的线程************");
            Thread.sleep(1000);
        }
        System.out.println("收到,马上!唤醒挂起的线程************");
        synchronized (a) {
            a.notifyAll();
        }
    }

    class TestTask implements Runnable {

        @Override
        public void run() {
            synchronized (a) {
                try {
                    for (int i = 10; i > 0; i--) {
                        Thread.sleep(1000);
                        System.out.println("我在运行 ***************");
                    }
                    a.wait();
                    for (int i = 10; i > 0; i--) {
                        System.out.println("谢谢唤醒**********又开始运行了*******");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
Copy after login

用wait notify 解决生产者消费者问题代码:

package com.taobao.concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class Meal {
    private final int orderNum;

    public Meal(int orderNum) {
        this.orderNum = orderNum;
    }

    public String toString() {
        return "Meal " + orderNum;
    }
}

class WaitPerson implements Runnable {
    private Restaurant restaurant;

    public WaitPerson(Restaurant r) {
        this.restaurant = r;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                synchronized (this) {
                    while (restaurant.meal == null)
                        wait();// ..for the chef to produce a meal
                }
                System.out.println("WaitPerson got" + restaurant.meal);
                synchronized (restaurant.chef) {
                    restaurant.meal = null;
                    restaurant.chef.notifyAll();// ready for another
                }
            }
            TimeUnit.MICROSECONDS.sleep(100);
        } catch (InterruptedException e) {
            System.out.println("WaitPerson interrupted");
        }
    }
}

class Chef implements Runnable {
    private Restaurant restaurant;
    private int count = 0;

    public Chef(Restaurant r) {
        this.restaurant = r;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                synchronized (this) {
                    while (restaurant.meal != null)
                        wait();// ...for the meal to be taken
                }
                if (++count == 10) {
                    System.out.println("Out of food,closing");
                    restaurant.exec.shutdownNow();
                }
                System.out.println("Order up!");
                synchronized (restaurant.waitPerson) {
                    restaurant.meal = new Meal(count);
                    restaurant.waitPerson.notifyAll();
                }

            }
        } catch (InterruptedException e) {
        }
    }
}

public class Restaurant {
    Meal meal;
    ExecutorService exec = Executors.newCachedThreadPool();
    WaitPerson waitPerson = new WaitPerson(this);
    Chef chef = new Chef(this);

    public Restaurant() {
        exec.execute(chef);
        exec.execute(waitPerson);
    }
    public static void main(String[] args) {
        new Restaurant();
    }

}
Copy after login

用ArrayBlockingQueue解决生产者消费者问题 ;默认使用的是非公平锁

take():取走BlockingQueue里排在首位的对象,若BlockingQueue为空,阻断进入等待状态直到Blocking有新的对象被加入为止,若请求不到此线程被加入阻塞队列;

如果使用公平锁,当有内容可以消费时,会从队首取出消费者线程进行消费(即等待时间最长的线程)

add(anObject):把anObject加到BlockingQueue里,即如果BlockingQueue可以容纳,则返回true,否则招聘异常

package com.taobao.concurrency;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class TestBlockingQueues {

    public static void main(String[] args) {
        BlockingQueue<String> queue = new ArrayBlockingQueue<String>(20);
        Thread pro = new Thread(new Producer(queue), "生产者");
        pro.start();
        for (int i = 0; i < 10; i++) {
            Thread t = new Thread(new Concumer(queue), "消费者 " + i);
            t.start();
        }

    }

}

class Producer implements Runnable {
    BlockingQueue<String> queue;

    public Producer(BlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {

        int i = 0;
        while (true) {
            try {
                System.out.println("生产者生产食物, 食物编号为:" + i);
                queue.put(" 食物 " + i++);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("生产者被中断");
            }
        }
    }
}

class Concumer implements Runnable {
    BlockingQueue<String> queue;

    public Concumer(BlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        while (true) {
            try {
                System.out.println(Thread.currentThread().getName() + "消费:"
                        + queue.take());
            } catch (InterruptedException e) {
                System.out.println("消费者被中断");
            }
        }
    }
}


执行结果:
消费者 0 请求消费
消费者 2 请求消费
消费者 4 请求消费
消费者 6 请求消费
消费者 8 请求消费
消费者 5 请求消费
生产者生产食物, 食物编号为:0
消费者 0消费: 食物 0
消费者 1 请求消费
消费者 3 请求消费
消费者 7 请求消费
消费者 9 请求消费
消费者 0 请求消费
生产者生产食物, 食物编号为:1
消费者 2消费: 食物 1
消费者 2 请求消费
生产者生产食物, 食物编号为:2
消费者 4消费: 食物 2
消费者 4 请求消费
生产者生产食物, 食物编号为:3
消费者 6消费: 食物 3
消费者 6 请求消费
生产者生产食物, 食物编号为:4
消费者 8消费: 食物 4
消费者 8 请求消费
生产者生产食物, 食物编号为:5
消费者 5消费: 食物 5
消费者 5 请求消费
生产者生产食物, 食物编号为:6
消费者 1消费: 食物 6
消费者 1 请求消费
生产者生产食物, 食物编号为:7
消费者 3消费: 食物 7
消费者 3 请求消费
生产者生产食物, 食物编号为:8
消费者 7消费: 食物 8
消费者 7 请求消费
生产者生产食物, 食物编号为:9
消费者 9消费: 食物 9
消费者 9 请求消费
Copy after login

多个生产者,多个消费者

package com.taobao.concurrency;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class TestBlockingQueues {

    public static void main(String[] args) {
        BlockingQueue<String> queue = new ArrayBlockingQueue<String>(20);
        for (int i = 0; i < 10; i++) {
            Thread pro = new Thread(new Producer(queue), "生产者" + i);
            pro.start();
        }
        for (int i = 0; i < 10; i++) {
            Thread t = new Thread(new Concumer(queue), "消费者 " + i);
            t.start();
        }

    }

}

class Producer implements Runnable {
    BlockingQueue<String> queue;

    public Producer(BlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {

        int i = 0;
        while (true) {
            try {
               
                    System.out.println(Thread.currentThread().getName()
                            + "生产食物, 食物编号为:" + Thread.currentThread().getName()
                            + i);
                    queue.put(" 食物 " + Thread.currentThread().getName() + i++);
                    Thread.sleep(10000);
               
            } catch (InterruptedException e) {
                System.out.println("生产者被中断");
            }
        }
    }
}

class Concumer implements Runnable {
    BlockingQueue<String> queue;

    public Concumer(BlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        while (true) {
            System.out.println(Thread.currentThread().getName() + " 请求消费");
            try {
                System.out.println(Thread.currentThread().getName() + "消费:"
                        + queue.take());
                Thread.sleep(100);
            } catch (InterruptedException e) {
                System.out.println("消费者被中断");
            }
        }
    }
}

生产者0生产食物, 食物编号为:生产者00
生产者2生产食物, 食物编号为:生产者20
生产者1生产食物, 食物编号为:生产者10
生产者3生产食物, 食物编号为:生产者30
生产者4生产食物, 食物编号为:生产者40
生产者6生产食物, 食物编号为:生产者60
生产者8生产食物, 食物编号为:生产者80
生产者5生产食物, 食物编号为:生产者50
生产者7生产食物, 食物编号为:生产者70
生产者9生产食物, 食物编号为:生产者90
消费者 0 请求消费
消费者 0消费: 食物 生产者00
消费者 2 请求消费
消费者 2消费: 食物 生产者20
消费者 1 请求消费
消费者 1消费: 食物 生产者10
消费者 4 请求消费
消费者 4消费: 食物 生产者30
消费者 3 请求消费
消费者 6 请求消费
消费者 6消费: 食物 生产者40
消费者 3消费: 食物 生产者60
消费者 8 请求消费
消费者 8消费: 食物 生产者80
消费者 5 请求消费
消费者 5消费: 食物 生产者50
消费者 7 请求消费
消费者 7消费: 食物 生产者70
消费者 9 请求消费
消费者 9消费: 食物 生产者90
消费者 0 请求消费
消费者 1 请求消费
消费者 2 请求消费
消费者 4 请求消费
消费者 3 请求消费
消费者 5 请求消费
消费者 7 请求消费
消费者 9 请求消费
消费者 6 请求消费
消费者 8 请求消费
生产者0生产食物, 食物编号为:生产者01
消费者 0消费: 食物 生产者01
生产者2生产食物, 食物编号为:生产者21
生产者4生产食物, 食物编号为:生产者41
消费者 1消费: 食物 生产者21
生产者1生产食物, 食物编号为:生产者11
消费者 2消费: 食物 生产者41
消费者 4消费: 食物 生产者11
生产者3生产食物, 食物编号为:生产者31
Copy after login

条件队列解释:

Condition queuesare like the "toast is ready" bell on your toaster. If you are 
list
ening for it, you are notified promptly when your toast is ready and can drop what you are doing (or not, maybe you want to finish the newspaper first) and get your toast. If you are not listening for it (perhaps you went outside to get the newspaper), you could miss the notification, but on return to the kitchen you can observe the state of the toaster and either retrieve the toast if it is finished or start listening for the bell again if it is not.
Copy after login

基于条件的:多线程情况下,某个条件在某个时刻为假,不代表一直为假,可能到某个时刻就好了!

Lock 使用的默认 为非公平锁;condition对象继承了与之相关的锁的共平性特性,如果是公平的锁,线程会依照FIFO的顺序从Condition.wait中被释放;ArrayBlockingQueue中有一个比较不好的地方,生产者每次生产完之后,都要通知消费者,至于有没有性能损失TODO

【相关推荐】

1. 详解java 中valueOf方法实例

2. JMM java内存模型图文详解

3.详细介绍Java内存区域与内存溢出异常

4. JavaScript中的object转换函数toString()与valueOf()介绍_javascript技巧

The above is the detailed content of Detailed tutorial on the thread memory model in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template