高并发编程系列(二)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_43874301/article/details/102383087

高并发编程系列(二)

High concurrency programming series

程序在执行过程中,如果出现异常,默认状况锁会被释放
所以,在并发处理过程中,有异常要多加小心,不然会发生不一致的情况,
比如,在一个web app处理过程中,多个servlet线程共同访问同一个资源,这时如果异常处理不适合,
在第一个线程中抛出异常,其他线程进入同步代码区,有可能访问到异常产生的数据.
因此要非常小心的处理同步业务逻辑中的异常
此案例 t1 锁被释放 t2 方可开始
若你不想释放锁请你加入try{}catch{}

public class Tj {

    int count = 0;
    synchronized void m() {
        System.out.println(Thread.currentThread().getName() + "start");
        while (true) {
            count ++;
            System.out.println(Thread.currentThread().getName() + "count: " + count);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (count == 5) {
                //此处抛出异常,锁将被释放,要想不释放就在此处进行catch,然后循环继续.
                int i = 1/0;
            }

        }
    }

    public static void main(String[] args) {

        Tj t = new Tj();
        Runnable r = new Runnable() {
            @Override
            public void run() {
                t.m();
            }
        };

        new Thread(r,"t1").start();

        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(r,"t2").start();

    }

}

运行结果

volatile 关键字,使一个变量在多个线程之间可见
A B 线程都用到一个变量,java默认是A线程中保留一份copy,这样如果B线程修改了该变量,则A线程未必知道.
使用volatile 关键字,会让所有线程都会读到变量值的修改.
在下面代码中,running是存在于堆内存的t对象中,
当线程t1开始运行的时候,会把running的值从内存中读到t1线程的工作区,在运行过程中,直接使用copy,
并不是每次都去使用colatile,将会强制所有线程去堆内存中读取running的值
olatile 并不能保证多个线程共同修改running变量时所带来的一直问题,也就说volatile不能代替synchronized

public class Tk {

    //对比一下有无volatitle ,整个程序运行结果的区别
    /*volatile*/ boolean running = true;
    void m(){
        System.out.println("m statr");
        while (running) {

        }
        System.out.println("m end");
    }

    public static void main(String[] args) {
        Tk t = new Tk();

        new Thread(t::m,"t1").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t.running = false;

    }

}

有volatile

volatile 并不能保证多个线程共同修改running 变量 时所带来的不一致问题,也就是说volatile 不能代替synchronized
运行下面的程序,分析结果
创建10个线程
volatile 和 synchronized 的区别
volatile 保证可见性并不保证原子性;synchronized 既保证可见性又保证原子性;
synchronized的效率要比volatile低不少 面试必出

public class Tl {

    volatile int count = 10;
    void m() {
        for (int i=0; i<10000;i++) count++;
    }

    public static void main(String[] args) {
        Tl t = new Tl();

        List<Thread> threads = new ArrayList<Thread>();

        for (int i=0; i<10; i++) {
            threads.add(new Thread(t::m, "thread" + i));
        }

        threads.forEach((o)->o.start());

        threads.forEach((o)->{
            try {
                o.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println(t.count);

    }

}

运行情况
运行情况

解决同样的问题的更高效的方法,使用AtomXXX类.原子类
AtmXXX类本身方法都是原子性的,但是不能保证多个方法调用是原子性的.

public class Tm {

    /*volatile int count = 0;*/

    AtomicInteger count = new AtomicInteger(0);

    synchronized void m(){
        for (int i=0; i<10000; i++)
            //if(count.get()<1000)      注意这里     如果未加锁,之间还会有其他线程插进来
            count.incrementAndGet(); //count++
    }

    public static void main(String[] args) {

        Tm  t = new Tm();

        List<Thread> threads = new ArrayList<Thread>();

        for (int i=0; i<10; i++) {
            threads.add(new Thread(t::m,"thread" + i));
        }

        threads.forEach((o)->o.start());

        threads.forEach((o)->{
            try {
                o.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println(t.count);

    }

}

运行结果

volatile 关键字,使一个变量在多个线程之间可见
A B 线程都用到一个变量,java默认是A线程中保留一份copy,这样如果B线程修改了该变量,则A线程未必知道.
使用volatile 关键字,会让所有线程都会读到变量值的修改.
在下面代码中,running是存在于堆内存的t对象中,
当线程t1开始运行的时候,会把running的值从内存中读到t1线程的工作区,在运行过程中,直接使用copy,
并不是每次都去使用colatile,将会强制所有线程去堆内存中读取running的值
volatile 并不能保证多个线程共同修改running变量时所带来的一直问题,也就说volatile不能代替synchronized

public class Tk {

    //对比一下有无volatitle ,整个程序运行结果的区别
    /*volatile*/ boolean running = true;
    void m(){
        System.out.println("m statr");
        while (running) {

        }
        System.out.println("m end");
    }

    public static void main(String[] args) {
        Tk t = new Tk();

        new Thread(t::m,"t1").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t.running = false;

    }

}

不加volatile
不添加volatile
添加volatile
添加volatile

volatile 并不能保证多个线程共同修改running 变量 时所带来的不一致问题,也就是说volatile 不能代替synchronized
运行下面的程序,分析结果
创建10个线程
volatile 和 synchronized 的区别
volatile 保证可见性并不保证原子性;synchronized 既保证可见性又保证原子性;
synchronized的效率要比volatile低不少 面试必出

public class Tl {

    volatile int count = 10;
    void m() {
        for (int i=0; i<10000;i++) count++;
    }

    public static void main(String[] args) {
        Tl t = new Tl();

        List<Thread> threads = new ArrayList<Thread>();

        for (int i=0; i<10; i++) {
            threads.add(new Thread(t::m, "thread" + i));
        }

        threads.forEach((o)->o.start());

        threads.forEach((o)->{
            try {
                o.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println(t.count);

    }

}

运行结果1
运行结果2

解决同样的问题的更高效的方法,使用AtomXXX类.原子类
AtmXXX类本身方法都是原子性的,但是不能保证多个方法调用是原子性的.

public class Tm {

    /*volatile int count = 0;*/

    AtomicInteger count = new AtomicInteger(0);

    synchronized void m(){
        for (int i=0; i<10000; i++)
            //if(count.get()<1000)             如果未加锁,之间还会有其他线程插进来
            count.incrementAndGet(); //count++
    }

    public static void main(String[] args) {

        Tm  t = new Tm();

        List<Thread> threads = new ArrayList<Thread>();

        for (int i=0; i<10; i++) {
            threads.add(new Thread(t::m,"thread" + i));
        }

        threads.forEach((o) -> o.start());

        threads.forEach((o) -> {
            try {
                o.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println(t.count);

    }

}

运行结果

synchonized优化.
同步代码块中的语句越少越好.
比较m1和m2

public class Tn {

    int count = 0;
    synchronized void m1() {

        //do sth need sync
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //业务逻辑中只有下面这句需要synchronized,这时不应该给整个方法上都上锁
        count++;

        //do sth need not sync
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    void m2() {
        //do sth need not sync
        try{
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //业务逻辑中只有下面这句需要sync 时不应该给整个方法上锁
        //采用细粒度的锁,可以使线程争用时间变短,从而提高效率  细粒度锁要比粗粒度锁效率要高
        synchronized (this) {
            count++;
        }
        //do sth need not sync
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //do sth not sync
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}

锁定某个对象o,如果o的属性发生改变,不影响使用.
但是如果o变成另外一个对象,则锁定的对象发生改变.
应该避免将锁定对象的引用变成另外对象

public class To {

    Object o = new Object();

    void m() {
        synchronized (o) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
        }
    }

    public static void main(String[] args) {
       To t = new To();
       //启动线程
        new Thread(t::m, "t1").start();

        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //创建第二个线程
        Thread t2 = new Thread(t::m, "t2");
        //锁定对象发生变化,所以t2线程得以进行,如注释掉这句话,线程2将永远得不到执行机会
        //锁是锁在堆内存  不是锁在栈内存
        t.o = new Object();

        t2.start();

    }

}

不要以字符串常量作为锁定对象
在下面m1 m2 其实锁定的是同一个对象
这种情况下还会发生比较诡异的现象,比如你用到了一个类库,在该类库中的代码锁定了"Hello",
但是你都不到源码,所以你在自己的代码中锁定了"Hello",这时候有可能发生非常诡异的死锁阻塞,
因为你的程序和你用到的类库不经意间使用了同一把锁.

public class Tp {

    String s1 = "Hello";
    String s2 = "Hello";

    void m1() {
        synchronized (s1) {

        }
    }

    void m2() {
        synchronized (s2) {

        }
    }
    
}

曾经的面试题
实现一个容器,提供两个方案 add size
写两个线程,线程添加十个元素到容器中,线程2实现监控元素个数,当个数到5个时,线程2给出提示并结束.
但是,t2线程死循环很浪费cpu,如果不用死循环,该怎么做呢?

public class Tq {

    //添加volatile 使t2能够得到通知

    volatile List lists = new ArrayList();

    public void add(Object o) {
        lists.add(o);
    }

    public int size() {
        return lists.size();
    }

    public static void main(String[] args) {
        Tq t = new Tq();

        new Thread(()-> {
           for (int i=0; i<10; i++) {
               t.add(new Object());
               System.out.println("add" + i);
           }

           try {
               TimeUnit.SECONDS.sleep(1);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
        },"t1").start();

        new Thread(()-> {
           while (true) {
               if (t.size() == 5) {
                   break;
               }
           }
            System.out.println("t2结束");
        },"t2").start();

    }

}

这里使用wait 和notify做到,wait会释放锁,而notify不会释放锁
需要注意的是这种方法必须保证t2先执行,也就是让t2监听才可以.
阅读下面的程序,并分析输出结果.
可以读到输出结果并不是size=5 t2退出,而是t1结束时t2才可以接收到通知推出
思考为什么
wait 是调用被锁定对象的wait方法 notify

public class Ts {

    volatile List lists = new ArrayList();

    public void add(Object o) {
        lists.add(o);
    }

    public int size() {
        return lists.size();
    }

    public static void main(String[] args) {
        Ts t = new Ts();

        final Object lock = new Object();

        new Thread(() -> {
           synchronized(lock) {
               System.out.println("t2启动");
               if (t.size() != 5) {
                   try {
                       lock.wait();
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               }
               System.out.println("t2结束");
           }
        },"t2").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            System.out.println("t1启动");
            synchronized(lock) {
                for (int i=0; i<10; i++) {
                    t.add(new Object());
                    System.out.println("add" + i);

                    if (t.size() == 5) {
                        lock.notify();
                    }

                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        },"t1").start();

    }

}

运行结果

这里是当size=5时,t1线程等,释放锁同时叫醒t2,t2执行,t2执行结束调用notify叫醒t1。

public class Tt {

    volatile List lists = new ArrayList();

    public void add(Object o) {
        lists.add(o);
    }

    public int size() {
        return lists.size();
    }

    public static void main(String[] args) {
        Ts t = new Ts();

        final Object lock = new Object();

        new Thread(() -> {
            synchronized(lock) {
                System.out.println("t2启动");
                if (t.size() != 5) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("t2结束");
                //通知t1继续执行·
                lock.notify();
            }
        },"t2").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            System.out.println("t1启动");
            synchronized(lock) {
                for (int i=0; i<10; i++) {
                    t.add(new Object());
                    System.out.println("add" + i);

                    if (t.size() == 5) {
                        lock.notify();
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        },"t1").start();

    }

}

运行结果

猜你喜欢

转载自www.cnblogs.com/mzdljgz/p/11641707.html