美文网首页
Java 多线程(二)线程间通信

Java 多线程(二)线程间通信

作者: GIT提交不上 | 来源:发表于2019-09-25 00:24 被阅读0次

一、volatile关键字

  volatile修饰成员变量,告知程序任何对该变量的访问均需要从共享内存中获取,而对它的改变必须同步刷新回共享内存,它能保证所有线程对变量访问的可见性。
  happen-before规则:如果a happen-before b,则a所做的任何操作对b是可见的。JVM底层是通过一个叫做“内存屏障”的东西来完成。内存屏障,也叫做内存栅栏,是一组处理器指令,用于实现对内存操作的顺序限制。
  volatile只能保证对单次读/写的原子性,改volatile变量分为四步:1)读取volatile变量到local;2)修改变量值;3)local值写回 ;4)插入内存屏障,即lock指令,让其他线程可见。前三步都是不安全的,取值和写回之间,不能保证没有其他线程修改。

public class Test implements Runnable {
    private volatile int a = 0;
    public void update() {
        a++;
    }
    @Override
    public void run() {
        try {
            Thread.sleep(10);  //增加并发几率
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.update();
    }

    public static void main(String[] args) {
        Test test = new Test();
        for (int i = 0; i < 1000; i++) {
            new Thread(test).start();
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(test.a); //输出的值不确定
    }
}

  适用场景:
  1)对变量的写操作不依赖于当前值;
  2)该变量没有包含在具有其他变量的不变式中。

二、synchronized关键字

  synchronized用来修饰方法或者代码块。确保多个线程在同一时刻,只能有一个线程处于方法或同步块中,它保证线程对变量的访问的可见性和排他性。

public class Test implements Runnable {
    private volatile int a = 0;
    public synchronized void update() {
        a++;
    }
    @Override
    public void run() {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.update();
    }
    public static void main(String[] args) {
        synchronized (Test.class){
            
        }
        Test test = new Test();
        new Thread(test).start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(test.a);
    }
}

  通过如下命令查看字节码文件:

javac Test.java
javap -v Test.class

图2-1 字节码同步块.png 图2-2 字节码同步方法.png

  通过查看字节码文件,synchronized对于同步块的实现使用了monitorenter和monitorexit指令,同步方法依靠方法修饰符上的ACC_SYNCHRONIZED实现。本质都是通过对一个对象的监视器(monitor)来实现,同一时刻只能有一个线程获取到有synchronized所保护对象的监视器(排他性)。

三、等待/通知机制

  等待/通知经典范式,分为等待方(消费者)和通知方(生产者)。等待方:1)获取对象的锁;2)如果条件不满足,那么调用对应的wait()方法,被通知后仍要检查条件;3)条件满足则执行对应的逻辑。

//伪代码
synchronized(对象){
    while(条件不满足){
          对象.wait();
    }
      对应的处理逻辑
}

  通知方:1)获取对象的锁;2)改变条件;3)通知所有等待在对象上的线程。

//伪代码
synchronized(对象){
    改变条件
    对象.notifyAll();
}

  等待方Consumer代码如下所示:

class Consumer implements Runnable {
    private LinkedList<String> list;
    public Consumer(LinkedList<String> list) {
        this.list = list;
    }
    public void update() {
        list.remove();
        System.out.println("开始消费!!!" + list.size());
        list.notifyAll();
    }
    @Override
    public void run() {
        while (true) {
            synchronized (list) {
                while (list.size() == 0) {
                    try {
                        System.out.println("不够吃!!!" + list.size());
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                this.update();
            }
        }
    }
}

  通知方Producer代码如下所示:

class Producer implements Runnable {
    private LinkedList<String> list;
    public Producer(LinkedList<String> list) {
        this.list = list;
    }
    public void update() {
        list.add("hello" + Math.random());
        System.out.println("开始生产!!!" + list.size());
        list.notifyAll();
    }
    @Override
    public void run() {
        while (true) {
            synchronized (list) {
                while (list.size() == 10) {
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("已满!!!");
                }
                this.update();
            }
        }
    }
}

  测试类代码如下所示:

public class Test {
    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<>();

        Consumer consumer = new Consumer(list);
        Producer producer = new Producer(list);

        Thread t2 = new Thread(consumer);
        Thread t3 = new Thread(consumer);
        t2.start();
        t3.start();

        Thread t = new Thread(producer);
        t.start();
    }
}

相关文章

网友评论

      本文标题:Java 多线程(二)线程间通信

      本文链接:https://www.haomeiwen.com/subject/fjpmuctx.html