简单聊聊 Java线程的并发

哈喽大家好,上一篇文章我们聊了聊Java线程的基础知识,这一篇文章我们就来聊聊线程中的线程安全问题

线程安全问题

线程安全问题一般指的是多个线程同时同一个变量进行操作的时候可能会出现问题。

我们先举个简单的例子来说说什么是线程安全问题:

public class symain {

    public static int a = 0;

    public static void main(String[] args) {
        TestThread testThread = new TestThread();
        Thread thread1 = new Thread(testThread,"A");
        Thread thread2 = new Thread(testThread,"B");
        Thread thread3 = new Thread(testThread,"C");
        thread1.start();
        thread2.start();
        thread3.start();
    }

    public static class TestThread extends Thread {

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                a++;
                System.out.println(currentThread().getName()+" a = "+a);
            }
        }
    }
}

结果为:

A a = 2
B a = 2
B a = 4
......

代码中a为公共变量,三个线程分别用for循环对a进行a++操作,结果中我们发现A和B同时出现了a为2的情况,这就是a的数据并没有及时同步到每一个线程,这就是我们所说的线程安全问题。


方法内部变量不存在线程安全问题

我们知道了线程安全问题的一个关键是对同一个变量进行操作,那么变量如果在方法内部,就不会造成线程安全问题了,虽然是同一个对象,但是方法中的变量是临时生成的,每调用一次方法就生成一个新的变量,所以不会造成线程安全问题,下面用代码验证下:

public class Test {
    
    public void test() {
        int a = 0;

        for (int i = 0; i < 10; i++) {
            a++;
            System.out.println(Thread.currentThread().getName() + " a = " + a);
        }
    }
}

public class symain {

    public static void main(String[] args) {
        Test test = new Test();
        TestThread testThread1 = new TestThread(test);
        TestThread testThread2 = new TestThread(test);
        TestThread testThread3 = new TestThread(test);
        testThread1.start();
        testThread2.start();
        testThread3.start();
    }

    public static class TestThread extends Thread {

        private Test test;

        public TestThread(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            test.test();
        }
    }
}

结果为:

Thread-0 a = 1
Thread-2 a = 1
Thread-2 a = 2
Thread-1 a = 1
Thread-1 a = 2
Thread-1 a = 3
Thread-2 a = 3
Thread-0 a = 2
Thread-2 a = 4
Thread-1 a = 4
Thread-2 a = 5
Thread-0 a = 3
Thread-2 a = 6
Thread-1 a = 5
Thread-1 a = 6
Thread-1 a = 7
Thread-1 a = 8
Thread-1 a = 9
Thread-1 a = 10
Thread-2 a = 7
Thread-0 a = 4
Thread-0 a = 5
Thread-2 a = 8
Thread-0 a = 6
Thread-0 a = 7
Thread-2 a = 9
Thread-0 a = 8
Thread-2 a = 10
Thread-0 a = 9
Thread-0 a = 10

我们可以看到虽然因为多线程执行的顺序有变化,但是每一个线程中的a是没有问题的。所以当变量在方法中的时候,是不存在线程安全问题的。


synchronized解决线程安全问题

那么有什么方法解决第一个例子的线程安全问题呢?Java为我们提供了关键字synchronized,我们在方法前加上这个关键字:

    public static class TestThread extends Thread {

        @Override
        synchronized public void run() {
            for (int i = 0; i < 10; i++) {
                a++;
                System.out.println(currentThread().getName()+" a = "+a);
            }
        }
    }

看下运行的结果:

A a = 1
A a = 2
A a = 3
A a = 4
A a = 5
A a = 6
A a = 7
A a = 8
A a = 9
A a = 10
C a = 11
C a = 12
C a = 13
C a = 14
C a = 15
C a = 16
C a = 17
C a = 18
C a = 19
C a = 20
B a = 21
B a = 22
B a = 23
B a = 24
B a = 25
B a = 26
B a = 27
B a = 28
B a = 29
B a = 30

上面的问题解决了。


synchronized对象锁

我们接下来看一个例子:

public class Test {

    synchronized public void test1() {
        try {
            System.out.println("test1 start");
            Thread.sleep(2000);
            System.out.println("test1 end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    synchronized public void test2() {
        System.out.println("test2 start");
        System.out.println("test2 end");
    }
}

public class symain {

    public static void main(String[] args) {
        Test test = new Test();
        ThreadA threadA = new ThreadA(test);
        ThreadB threadB = new ThreadB(test);
        threadA.start();
        threadB.start();
    }

    public static class ThreadA extends Thread {

        private Test test;

        public ThreadA(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            test.test1();
        }
    }

    public static class ThreadB extends Thread {

        private Test test;

        public ThreadB(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            test.test2();
        }
    }
}

结果为:

test1 start
test1 end
test2 start
test2 end

我们看到运行结果是按顺序运行的,证明同一个对象中,在方法前面加入了synchronized,这些方法获取的是同一个锁,并且他们获取的是对象锁。下面我们通过代码来验证下:

    public void test2() {
        synchronized (this) {
            System.out.println("test2 start");
            System.out.println("test2 end");
        }
    }

结果为:

test1 start
test1 end
test2 start
test2 end

验证了在方法前加synchronized和synchronized(this)的效果是相同的,他们都是以当前类生成的对象为监视器的,并且这种锁都是对象锁。

对象锁还有一个特性,那就是多个对象多个锁,我们来看一段代码:

public class Test {

    synchronized public void test1() {
        try {
            System.out.println("test1 start");
            Thread.sleep(2000);
            System.out.println("test1 end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    synchronized public void test2() {
        System.out.println("test2 start");
        System.out.println("test2 end");
    }
}

public class symain {

    public static void main(String[] args) {
        Test test1 = new Test();
        Test test2 = new Test();
        ThreadA threadA = new ThreadA(test1);
        ThreadB threadB = new ThreadB(test2);
        threadA.start();
        threadB.start();
    }

    public static class ThreadA extends Thread {

        private Test test;

        public ThreadA(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            test.test1();
        }
    }

    public static class ThreadB extends Thread {

        private Test test;

        public ThreadB(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            test.test2();
        }
    }
}

结果为:

test1 start
test2 start
test2 end
test1 end

当我们传入的Test并不是同一个对象的时候,结果也并不是按顺序打印,因为两个对象分别拿的是两个不同的锁。


synchronized锁重入

在拥有相同锁的前提下,加了锁的方法内部依然可以调用拥有相同锁的方法,下面我们来看看代码:

public class Test {

    synchronized public void test1() {
       System.out.println("in test1");
       test2();
    }

    synchronized public void test2() {
        System.out.println("in test2");
        test3();
    }

    synchronized public void test3(){
        System.out.println("in test3");
    }
}

public class symain {

    public static void main(String[] args) {
        Test test1 = new Test();
       ThreadTest threadTest = new ThreadTest(test1);
       threadTest.start();
    }

    public static class ThreadTest extends Thread {

        private Test test;

        public ThreadTest(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            test.test1();
        }
    }
}

结果为:

in test1
in test2
in test3

上面的代码证明了拥有相同锁的方法之间是可以互相调用的。

子类和父类之间也是可以实现锁重入的,我们来看看代码:

public class Test {

    synchronized public void test1() {
       System.out.println("in test1");
    }
}

public class TestMin extends Test {

    synchronized public void test2() {
        System.out.println("in test2");
        test1();
    }
}

public class symain {

    public static void main(String[] args) {
        TestMin testMin = new TestMin();
        ThreadA threadA = new ThreadA(testMin);
        threadA.start();
    }

    public static class ThreadA extends Thread {

        private TestMin testMin;

        public ThreadA(TestMin testMin) {
            this.testMin = testMin;
        }

        @Override
        public void run() {
            testMin.test2();
        }
    }
}

结果为:

in test2
in test1

我们可以看到在test2方法中还没有释放当前锁,我们成功的调用了父类的方法test1,证明了父类和子类之间也可以实现锁重入。


异常会释放锁

如果加锁的代码中出现了异常,那么这个锁就会自动释放掉,下面我们来看看代码:

public class Test {

    synchronized public void test1() {
        System.out.println("test1 start");
        int a = 100;

        while (true) {
            int b = 20 / a--;
            System.out.println("test1 b = " + b);
        }
    }

    synchronized public void test2() {
        System.out.println("in test2");
    }
}

public class symain {

    public static void main(String[] args) {
        Test test = new Test();
        ThreadA threadA = new ThreadA(test);
        ThreadB threadB = new ThreadB(test);
        threadA.start();
        threadB.start();
    }

    public static class ThreadA extends Thread {

        private Test test;

        public ThreadA(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            super.run();
            test.test1();
        }
    }

    public static class ThreadB extends Thread {

        private Test test;

        public ThreadB(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            super.run();
            test.test2();
        }
    }
}

结果为:

......
test1 b = 10
test1 b = 20
Exception in thread "Thread-0" java.lang.ArithmeticException: / by zero
    at Sydemo.Test.test1(Test.java:10)
    at Sydemo.symain$ThreadA.run(symain.java:24)
in test2

我们可以看到,早报错过后test1方法释放了锁,test2方法才开始运行。


同步不具有继承性

子类重写了父类的方法,如果父类方法前加了synchronized,那么子类方法中也必须加synchronized,要不就不具有锁的效果,我们来看看代码:

public class Test {

    synchronized public void test1() {
       try {
           System.out.println("test1 start");
           Thread.sleep(2000);
           System.out.println("test1 end");
       }catch (Exception e){
           e.printStackTrace();
       }
    }
}

public class TestMin extends Test {

    @Override
    public void test1() {
        try {
            System.out.println("test1 start");
            Thread.sleep(2000);
            System.out.println("test1 end");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    synchronized public void test2() {
        System.out.println("test2 start");
        System.out.println("test2 end");
    }
}

public class symain {

    public static void main(String[] args) {
        TestMin testMin = new TestMin();
        ThreadA threadA = new ThreadA(testMin);
        ThreadB threadB = new ThreadB(testMin);
        threadA.start();
        threadB.start();
    }

    public static class ThreadA extends Thread {

        private TestMin testMin;

        public ThreadA(TestMin testMin) {
            this.testMin = testMin;
        }

        @Override
        public void run() {
            super.run();
            testMin.test1();
        }
    }

    public static class ThreadB extends Thread {

        private TestMin testMin;

        public ThreadB(TestMin testMin) {
            this.testMin = testMin;
        }

        @Override
        public void run() {
            super.run();
            testMin.test2();
        }
    }
}

结果为:

test1 start
test2 start
test2 end
test1 end

我们可以看到test1还没有执行完成test2已经执行完成了,证明锁并没有起作用,我们将子类的test1方法加上synchronized试试。

    @Override
    public synchronized void test1() {
        try {
            System.out.println("test1 start");
            Thread.sleep(2000);
            System.out.println("test1 end");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

结果为:

test1 start
test1 end
test2 start
test2 end

这样才是正确的,所以子类在重写父类带有synchronized关键字方法的时候,也要加上synchronized关键字才行。


任意对象为对象监视器

对象监视器是什么呢,我们在使用synchronized(this)的时候,传入的this就是对象监视器,这个传入的值可以为任意值。我们一般会使用一个对象,或者是一个变量来充当这个对象监视器,下面我们举个例子:

public class Test {

    private final Object object = new Object();

    public void test1() {
        synchronized (object){
            try {
                System.out.println("test1 start");
                Thread.sleep(2000);
                System.out.println("test1 end");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void test2() {
        synchronized (object){
            System.out.println("test2 start");
            System.out.println("test2 end");
        }
    }
}

public class symain {

    public static void main(String[] args) {
        Test test = new Test();
        ThreadA threadA = new ThreadA(test);
        ThreadB threadB = new ThreadB(test);
        threadA.start();
        threadB.start();
    }

    public static class ThreadA extends Thread {

        private Test test;

        public ThreadA(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            super.run();
            test.test1();
        }
    }

    public static class ThreadB extends Thread {

        private Test test;

        public ThreadB(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            super.run();
            test.test2();
        }
    }
}

结果为:

test1 start
test1 end
test2 start
test2 end

我们在以object为对象监视器的时候,锁是起了作用的。需要注意的是要用同一个对象当监视器才行,如果是不同的对象,锁则不起作用。


方法前添加synchronized也有可能出现线程不安全

上面我们都说添加synchronized过后,线程就是安全的,但是有时候也会有特殊情况,这也是线程安全的难点,到处都是细节啊。我们下面来看个例子:

public class Test {

    private List list = new ArrayList<>();

    synchronized void addList() {
        list.add(1);
    }

    synchronized Integer getList() {
        return list.size();
    }
}

public class symain {

    public static void main(String[] args) {
        try {
            Test test = new Test();
            ThreadA threadA = new ThreadA(test);
            ThreadB threadB = new ThreadB(test);
            threadA.start();
            threadB.start();
            Thread.sleep(6000);
            System.out.println(test.getList());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static class ThreadA extends Thread {

        private Test test;

        public ThreadA(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            super.run();
            try {
                if (test.getList() < 1) {
                    Thread.sleep(2000);
                    test.addList();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static class ThreadB extends Thread {

        private Test test;

        public ThreadB(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            super.run();
            try {
                if (test.getList() < 1) {
                    Thread.sleep(2000);
                    test.addList();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

结果为:

2

我们在Test类中的两个方法都加入了synchronized关键字,这两个方法的调用时线程安全的,但是我们在调用的时候有一个时间差,就造成了最后的错误,像这种情况,我们可以用synchronized代码块来解决:

    public static class ThreadA extends Thread {

        private Test test;

        public ThreadA(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            super.run();
            synchronized (test) {
                try {
                    if (test.getList() < 1) {
                        Thread.sleep(2000);
                        test.addList();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static class ThreadB extends Thread {

        private Test test;

        public ThreadB(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            super.run();
            synchronized (test) {
                try {
                    if (test.getList() < 1) {
                        Thread.sleep(2000);
                        test.addList();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

我们线程中加入了以test为线程监视器的synchronized代码块,我们来看看结果:

1

最后结果为正常的。


synchronized静态方法和synchronized(.Class)

synchronized如果加在静态方法前面,线程监视器就为当前类,我们举个例子:

public class Test {

    public synchronized static void test1() {
        try {
            System.out.println("test1 start");
            Thread.sleep(2000);
            System.out.println("test2 end");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void test2() {
        synchronized (Test.class) {
            System.out.println("test2 start");
            System.out.println("test2 end");
        }
    }
}

public class symain {

    public static void main(String[] args) {

        Test test = new Test();
        ThreadA threadA = new ThreadA();
        ThreadB threadB = new ThreadB(test);
        threadA.start();
        threadB.start();

    }

    public static class ThreadA extends Thread {

        @Override
        public void run() {
            super.run();
            Test.test1();
        }
    }

    public static class ThreadB extends Thread {

        private Test test;

        public ThreadB(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            super.run();
            test.test2();
        }
    }
}

结果为:

test1 start
test1 end
test2 start
test2 end

证明了他们的线程监视器都是Test.Class这个类。

当使用类当线程监视器的时候,对这个类的所有对象都是起作用的,下面我们来看看代码:

public class Test {

    public void test1() {
        synchronized (Test.class) {
            try {
                System.out.println("test1 start");
                Thread.sleep(2000);
                System.out.println("test1 end");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void test2() {
        synchronized (Test.class) {
            System.out.println("test2 start");
            System.out.println("test2 end");
        }
    }
}

public class symain {

    public static void main(String[] args) {
        Test test1 = new Test();
        Test test2 = new Test();
        ThreadA threadA = new ThreadA(test1);
        ThreadB threadB = new ThreadB(test2);
        threadA.start();
        threadB.start();
    }

    public static class ThreadA extends Thread {

        private Test test;

        public ThreadA(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            super.run();
            test.test1();
        }
    }

    public static class ThreadB extends Thread {

        private Test test;

        public ThreadB(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            super.run();
            test.test2();
        }
    }
}

结果为:

test1 start
test1 end
test2 start
test2 end

我们传入的是两个不同的Test对象,但是最后的结果是同步的。所以这也验证了我们上面的说法。


死锁

死锁简单来说就是在使用synchronized的时候,因为使用不正确而造成进入有锁的方法后就无法出来了。我们举个例子来说明一下:

public class Test {

    private final Object object1 = new Object();
    private final Object object2 = new Object();

    public void test1() {

        synchronized (object1) {
            try {
                System.out.println("进入了test1第一次锁");
                Thread.sleep(2000);
                synchronized (object2) {
                    System.out.println("进入了test1的第二层锁");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void test2() {

        synchronized (object2) {
            try {
                System.out.println("进入了test2第一次锁");
                Thread.sleep(2000);
                synchronized (object1) {
                    System.out.println("进入了test2的第二层锁");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

public class symain {

    public static void main(String[] args) {
        Test test = new Test();
        ThreadA threadA = new ThreadA(test);
        ThreadB threadB = new ThreadB(test);
        threadA.start();
        threadB.start();
    }

    public static class ThreadA extends Thread {

        private Test test;

        public ThreadA(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            super.run();
            test.test1();
        }
    }

    public static class ThreadB extends Thread {

        private Test test;

        public ThreadB(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            super.run();
            test.test2();
        }
    }
}

结果为:

进入了test1第一次锁
进入了test2第一次锁

结果明显是代码没有走完,就一直困在了方法里面。我们来稍微分析一下,当第一个线程进入第一个方法的时候,持有了对象监视器为object1这个锁,然后准备等待2s后进入对象监视器为object2的这个锁,但是还没有到2s,第二个线程就进入了方法并且持有了对象监视器为object2的这个锁,这就造成了线程一要等线程二执行完这个方法并释放对象监视器为object2的锁后才能才能继续往下执行。但是线程二中也同样在等待线程一执行完成,释放对象监视器为object1的锁,所以他们就相互在等待,最后就困在了方法里面。


对象锁,对象的参数变化不会影响到锁

我们在使用任意一个对象为线程监视器的时候,如果我们修改了对象中的属性,并不会影响同步,我们举个例子:

public class User {

    private String name;
    private int age;

    public void setAge(int age) {
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }
}

public class Test {

    private final User user = new User();

    public Test() {
        user.setName("AAA");
        user.setAge(7);
    }

    public void test1() {

        synchronized (user) {
            try {
                System.out.println("test1 start");
                Thread.sleep(2000);
                System.out.println("test1 end");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void test2() {

        synchronized (user) {
            System.out.println("test2 start");
            System.out.println("test2 end");
        }
    }

    public void changeUser() {
        user.setAge(user.getAge() + 10);
        System.out.println("age修改为:" + user.getAge());
    }
}

public class symain {

    public static void main(String[] args) {
        try {
            Test test = new Test();
            ThreadA threadA = new ThreadA(test);
            ThreadB threadB = new ThreadB(test);
            threadA.start();
            Thread.sleep(500);
            test.changeUser();
            threadB.start();
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    public static class ThreadA extends Thread {

        private Test test;

        public ThreadA(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            super.run();
            test.test1();
        }
    }

    public static class ThreadB extends Thread {

        private Test test;

        public ThreadB(Test test) {
            this.test = test;
        }

        @Override
        public void run() {
            super.run();
            test.test2();
        }
    }
}

结果为:

test1 start
age修改为:17
test1 end
test2 start
test2 end

我们可以看到执行顺序依然是正常的。


有关synchronized关键字和线程安全的知识点就讲的差不多了,如果上文中有错误的地方欢迎大家指出。

3Q

你可能感兴趣的:(简单聊聊 Java线程的并发)