美文网首页
Java中的死锁,乐观锁

Java中的死锁,乐观锁

作者: 被虐的小鸡 | 来源:发表于2020-07-21 15:31 被阅读0次

    线程的创建方式

    纠正一下线程的创建方式,之前很多博客都写有三种方式,翻看了一下Thread的源码发现只有两种方式。
    1.继承Thread
    2.实现Runnable

     * There are two ways to create a new thread of execution. One is to
     * declare a class to be a subclass of <code>Thread</code>. This
     * subclass should override the <code>run</code> method of class
     * <code>Thread</code>. An instance of the subclass can then be
     * allocated and started. For example, a thread that computes primes
     * larger than a stated value could be written as follows:
     * <hr><blockquote><pre>
     *     class PrimeThread extends Thread {
     *         long minPrime;
     *         PrimeThread(long minPrime) {
     *             this.minPrime = minPrime;
     *         }
     *
     *         public void run() {
     *             // compute primes larger than minPrime
     *             &nbsp;.&nbsp;.&nbsp;.
     *         }
     *     }
     * </pre></blockquote><hr>
     * <p>
     * The following code would then create a thread and start it running:
     * <blockquote><pre>
     *     PrimeThread p = new PrimeThread(143);
     *     p.start();
     * </pre></blockquote>
     * <p>
     * The other way to create a thread is to declare a class that
     * implements the <code>Runnable</code> interface. That class then
     * implements the <code>run</code> method. An instance of the class can
     * then be allocated, passed as an argument when creating
     * <code>Thread</code>, and started. The same example in this other
     * style looks like the following:
     * <hr><blockquote><pre>
     *     class PrimeRun implements Runnable {
     *         long minPrime;
     *         PrimeRun(long minPrime) {
     *             this.minPrime = minPrime;
     *         }
     *
     *         public void run() {
     *             // compute primes larger than minPrime
     *             &nbsp;.&nbsp;.&nbsp;.
     *         }
     *     }
     * </pre></blockquote><hr>
     * <p>
     * The following code would then create a thread and start it running:
     * <blockquote><pre>
     *     PrimeRun p = new PrimeRun(143);
     *     new Thread(p).start();
     * </pre></blockquote>
     * <p>
    

    至于为什么实现Callable不能算作一种方式,是因为Callable我们需要交给FutureTask来处理,而FutureTask又是Runnable的子类。

    线程的状态

    回顾一下线程的状态
    1.可运行状态
    2.运行状态
    3.阻塞状态 使用synchronized加锁
    4.等待状态 使用wait,sleep,join以及显示锁
    5.死亡状态

    死锁

    死锁就是有两个线程或者两个以上线程,A线程获取了A资源之后还想获取B资源,B线程获取了B资源之后还想获取A资源,彼此都不放弃自己持有的资源。

    public class Lock {
        static ReentrantLock lock=new ReentrantLock();
        static ReentrantLock lock1=new ReentrantLock();
        static class ThreadA extends Thread{
    
            @Override
            public void run() {
                super.run();
                synchronized (lock){
                    System.out.println("lock");
    
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (lock1){
                        System.out.println("lock1");
                    }
                }
            }
        }
    
        static class ThreadB extends Thread{
            @Override
            public void run() {
                super.run();
                synchronized (lock1){
                    System.out.println("lock1");
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (lock){
                        System.out.println("lock");
                    }
                }
            }
        }
    
        public static void main(String[] args){
            new ThreadA().start();
    
            new ThreadB().start();
        }
    
    }
    

    死锁的条件:
    1.互斥条件
    2.保持持有资源
    3.不剥夺已有资源
    4.环路等待

    解决死锁

    1.设定请求锁的顺序

    public class Lock {
        static ReentrantLock lock=new ReentrantLock();
        static ReentrantLock lock1=new ReentrantLock();
        static class ThreadA extends Thread{
    
            @Override
            public void run() {
                super.run();
                synchronized (lock){
                    System.out.println("lock");
    
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (lock1){
                        System.out.println("lock1");
                    }
                }
            }
        }
    
        static class ThreadB extends Thread{
            @Override
            public void run() {
                super.run();
                synchronized (lock){
                    System.out.println("lock");
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (lock1){
                        System.out.println("lock1");
                    }
                }
            }
        }
    
        public static void main(String[] args){
            new ThreadA().start();
    
            new ThreadB().start();
        }
    
    }
    
    

    2.使用tryLock尝试请求锁

    public class Lock {
        static ReentrantLock lock = new ReentrantLock();
        static ReentrantLock lock1 = new ReentrantLock();
    
        static class ThreadA extends Thread {
    
            @Override
            public void run() {
                super.run();
                while (true) {
                    if (lock.tryLock()) {
                        System.out.println(Thread.currentThread().getName() + "lock");
                        try {
    
                            try {
                                sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
    
    
                            if (lock1.tryLock()) {
                                try {
                                    System.out.println(Thread.currentThread().getName() + "lock1");
                                    break;
                                } finally {
                                    lock1.unlock();
                                }
                            }
    
                        } finally {
                            lock.unlock();
                        }
    
                    }
                }
    
            }
        }
    
        static class ThreadB extends Thread {
            @Override
            public void run() {
                super.run();
                while (true) {
                    if (lock1.tryLock()) {
                        System.out.println(Thread.currentThread().getName() + "lock1");
                        try {
    
                            try {
                                sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
    
    
                            if (lock.tryLock()) {
                                try {
                                    System.out.println(Thread.currentThread().getName() + "lock");
                                    break;
                                } finally {
                                    lock.unlock();
                                }
                            }
    
                        } finally {
                            lock1.unlock();
                        }
                    }
                }
    
            }
        }
    
        public static void main(String[] args) {
            new ThreadA().start();
    
            new ThreadB().start();
        }
    
    }
    

    发现无法获取内部的锁,造成了活锁,线程还在一直运行但是无法执行内部的代码,一直在获取锁,释放锁。
    解决方法:
    在释放掉锁之后等待一段不同的时间

    public class Lock {
        static ReentrantLock lock = new ReentrantLock();
        static ReentrantLock lock1 = new ReentrantLock();
    
        static class ThreadA extends Thread {
    
            @Override
            public void run() {
                super.run();
                while (true) {
                    if (lock.tryLock()) {
                        System.out.println(Thread.currentThread().getName() + "lock");
                        try {
    
                            try {
                                sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
    
    
                            if (lock1.tryLock()) {
                                try {
                                    System.out.println(Thread.currentThread().getName() + "lock1");
                                    break;
                                } finally {
                                    lock1.unlock();
                                }
                            }
    
                        } finally {
                            lock.unlock();
                        }
    
                    }
                    try {
                        sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
    
            }
        }
    
        static class ThreadB extends Thread {
            @Override
            public void run() {
                super.run();
                while (true) {
                    if (lock1.tryLock()) {
                        System.out.println(Thread.currentThread().getName() + "lock1");
                        try {
    
                            try {
                                sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
    
    
                            if (lock.tryLock()) {
                                try {
                                    System.out.println(Thread.currentThread().getName() + "lock");
                                    break;
                                } finally {
                                    lock.unlock();
                                }
                            }
    
                        } finally {
                            lock1.unlock();
                        }
                    }
                    try {
                        sleep(3);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
    
            }
        }
    
        public static void main(String[] args) {
            new ThreadA().start();
    
            new ThreadB().start();
        }
    
    }
    
    

    ThreadLocal

    在Handler中使用了ThreadLocal用来保存Looper,使得每个线程有自己的Looper。可以起到数据隔离的作用。
    内部原理:
    由于每个Thread都有一个ThreadLocal.ThreadLocalMap的成员变量,ThreadLocalMap中存放了一个Entry[],key就是ThreadLocal,value就是存放的值。数组是因为一个线程可以有多个ThreadLocal。
    当ThreadLocal.set的时候,首先获取了当前线程的ThreadLocalMap。

    乐观锁(CAS) compare and swap

    通常我们使用的类锁,对象锁,显示锁都是悲观锁,当某一个线程拿到锁之后其他线程就无法拿到锁。
    乐观锁可以保证原子操作,在对变量进行操作的时候,多个线程可以同时进入代码执行,但是会携带一个初始的值,进入CAS的时候会拿着初始值和此线程携带的初始值进行比较,如果一致那么就可以将此线程的值进行更新。如果不一致那么就重新执行代码进行计算,然后再比较....此处是一个死循环

    乐观锁的问题

    1.ABA
    变量原始为A,线程1将变量修改为B,而线程2将变量修改成C,然后又修改成A,这个时候就出现问题了。
    解决方法:加入版本戳,可以理解为一个计数器,如果初始值相同,并且计数器为0,那么就是没有被别人修改过
    例如:AtomicMarkableReference(有版本戳),AtomicStampedReference(有版本戳并且可以获取被修改了几次)
    2.资源开支 线程竞争比较激烈的时候,死循环
    3.只能对一个变量进行原子操作 AtomicReference(将修改的变量封装成一个类,就可以对多个变量进行原子操作了)

    相关文章

      网友评论

          本文标题:Java中的死锁,乐观锁

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