https://www.imooc.com/video/6775
    image.png
    image.png
    image.png
    image.png
    image.png
    image.png
    image.png
    image.png
    image.png
    image.png
    image.png
    image.png
    image.png
    image.png
    image.png

    1. package mkw.demo.syn;
    2. public class SynchronizedDemo {
    3. //共享变量
    4. private boolean ready = false;
    5. private int result = 0;
    6. private int number = 1;
    7. //写操作
    8. public void write(){
    9. ready = true; //1.1
    10. number = 2; //1.2
    11. }
    12. //读操作
    13. public void read(){
    14. if(ready){ //2.1
    15. result = number*3; //2.2
    16. }
    17. System.out.println("result的值为:" + result);
    18. }
    19. //内部线程类
    20. private class ReadWriteThread extends Thread {
    21. //根据构造方法中传入的flag参数,确定线程执行读操作还是写操作
    22. private boolean flag;
    23. public ReadWriteThread(boolean flag){
    24. this.flag = flag;
    25. }
    26. @Override
    27. public void run() {
    28. if(flag){
    29. //构造方法中传入true,执行写操作
    30. write();
    31. }else{
    32. //构造方法中传入false,执行读操作
    33. read();
    34. }
    35. }
    36. }
    37. public static void main(String[] args) {
    38. SynchronizedDemo synDemo = new SynchronizedDemo();
    39. //启动线程执行写操作
    40. synDemo .new ReadWriteThread(true).start();
    41. try {
    42. Thread.sleep(1000);
    43. } catch (InterruptedException e) {
    44. // TODO Auto-generated catch block
    45. e.printStackTrace();
    46. }
    47. //启动线程执行读操作
    48. synDemo.new ReadWriteThread(false).start();
    49. }
    50. }

    image.png
    image.png
    image.png
    image.png
    image.png
    image.png
    image.png
    image.png
    image.png
    image.png
    image.png
    image.png
    image.png

    1. class Singleton{
    2. private volatile static Singleton instance = null;
    3. private Singleton() {
    4. }
    5. public static Singleton getInstance() {
    6. if(instance==null) {
    7. synchronized (Singleton.class) {
    8. if(instance==null)
    9. instance = new Singleton();
    10. }
    11. }
    12. return instance;
    13. }
    14. }

    细说Java多线程之内存可见性 - 图29