8.1 线程安全问题的主要诱因

  • 存在共享数据(也称临界资源)
  • 存在多条线程共同操作这些共享数据

    8.2 解决问题的根本方法

    同一时刻有且仅有一个线程在操作共享数据,其他线程必须等到该线程处理完数据后再对共享数据进行操作。

    8.3 互斥锁的特性

    互斥性:即在同一时间只允许一个线程持有某个对象锁,通过这种特性来实现多线程的协调机制,这样在同一时间只有一个线程对需要同步的代码块(复合操作)进行访问。互斥性也成为操作的原子性。
    可见性:必须确保在锁被释放之前,对共享变量所做的修改,对于随后获得该锁的另一个线程是可见的(即在获得锁时应获得最新共享变量的值),否则另一个线程可能是在本地缓存的某个副本上继续操作,从而引起不一致。
    synchronized 锁的不是代码,锁的都是对象

    8.4 锁的分类:获取对象锁和获取类锁

    获取对象锁的两种用法
  1. 同步代码块(synchronized(this),synchronized(类实例对象)),锁是小括号()中的实例对象。
  2. 同步非静态方法(synchronized method),锁是当前对象的实例对象。

下面看一个示例。

  1. package thread;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4. public class SyncThread implements Runnable {
  5. @Override
  6. public void run() {
  7. String threadName = Thread.currentThread().getName();
  8. if (threadName.startsWith("A")) {
  9. async();
  10. } else if (threadName.startsWith("B")) {
  11. syncObjectBlock1();
  12. } else if (threadName.startsWith("C")) {
  13. syncObjectMethod1();
  14. }
  15. }
  16. /**
  17. * 异步方法
  18. */
  19. private void async() {
  20. try {
  21. System.out.println(Thread.currentThread().getName() + "_Async_Start: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
  22. Thread.sleep(1000);
  23. System.out.println(Thread.currentThread().getName() + "_Async_End: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
  24. } catch (InterruptedException e) {
  25. e.printStackTrace();
  26. }
  27. }
  28. /**
  29. * 方法中有 synchronized(this|object) {} 同步代码块
  30. */
  31. private void syncObjectBlock1() {
  32. System.out.println(Thread.currentThread().getName() + "_SyncObjectBlock1: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
  33. synchronized (this) {
  34. try {
  35. System.out.println(Thread.currentThread().getName() + "_SyncObjectBlock1_Start: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
  36. Thread.sleep(1000);
  37. System.out.println(Thread.currentThread().getName() + "_SyncObjectBlock1_End: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
  38. } catch (InterruptedException e) {
  39. e.printStackTrace();
  40. }
  41. }
  42. }
  43. /**
  44. * synchronized 修饰非静态方法
  45. */
  46. private synchronized void syncObjectMethod1() {
  47. System.out.println(Thread.currentThread().getName() + "_SyncObjectMethod1: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
  48. try {
  49. System.out.println(Thread.currentThread().getName() + "_SyncObjectMethod1_Start: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
  50. Thread.sleep(1000);
  51. System.out.println(Thread.currentThread().getName() + "_SyncObjectMethod1_End: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
  52. } catch (InterruptedException e) {
  53. e.printStackTrace();
  54. }
  55. }
  56. }
package thread;

public class SyncDemo {
    public static void main(String... args) {
        SyncThread syncThread = new SyncThread();
        Thread A_thread1 = new Thread(syncThread, "A_thread1");
        Thread A_thread2 = new Thread(syncThread, "A_thread2");
        Thread B_thread1 = new Thread(syncThread, "B_thread1");
        Thread B_thread2 = new Thread(syncThread, "B_thread2");
        Thread C_thread1 = new Thread(syncThread, "C_thread1");
        Thread C_thread2 = new Thread(syncThread, "C_thread2");
        A_thread1.start();
        A_thread2.start();
        B_thread1.start();
        B_thread2.start();
        C_thread1.start();
        C_thread2.start();
    }
}

image.png
从结果中发现,A_thread1_Async_Start 和 A_thread2_Async_Start 这两个线程是异步执行的,因为 A_thread1_Async 在开始后并没有结束,A_thread2_Async 就开始执行了,并且还先完成。同时我们也能看到,A 类的线程并未受到其他使用同步锁的方式去执行的线程的影响。之所以不受同步的影响是因为 A 类线程里并没有同步代码块,即没有获取同步锁的需求。
B 类线程是同步的。一个线程在访问对象的代码块时,另外一个访问对象同步代码块的线程会被阻塞。从图中可以看到 B_thread1_SyncObjectBlock1_Start 先执行,B_thread2_SyncObjectBlock1_Start 线程需要等待 B_thread1_SyncObjectBlock1_End 结束才能够执行,因此是顺序执行的,原因在这个方法中需要获取同步锁,但是 synchronized 代码块之外的语句是异步的,可以看到 B_thread1_SyncObjectBlock1 和 B_thread2_SyncObjectBlock1 先打印。
C 类线程也是同步的,即一个线程在访问同步方法的时候,另一个访问对象同步方法的线程会被阻塞。
通过 B 类线程和 C 类线程的比较,我们可以发现本次执行时 C 类线程先运行,除非执行完成,否则 B 类线程不会执行,这说明同步方法和同步块锁的是同一个对象。
下面测试锁不同的对象。

package thread;

public class SyncDemo {
    public static void main(String... args) {
        SyncThread syncThread = new SyncThread();
        Thread A_thread1 = new Thread(new SyncThread(), "A_thread1");
        Thread A_thread2 = new Thread(new SyncThread(), "A_thread2");
        Thread B_thread1 = new Thread(new SyncThread(), "B_thread1");
        Thread B_thread2 = new Thread(new SyncThread(), "B_thread2");
        Thread C_thread1 = new Thread(new SyncThread(), "C_thread1");
        Thread C_thread2 = new Thread(new SyncThread(), "C_thread2");
        A_thread1.start();
        A_thread2.start();
        B_thread1.start();
        B_thread2.start();
        C_thread1.start();
        C_thread2.start();
    }
}

image.png
从图中可以看出三个线程都变成异步,如 C_thread2_SyncObjectMethod1_Start 开始执行,B_thread2_SyncObjectBlock1_Start 紧随其后执行,C_thread1_SyncObjectMethod1_Start 也不会等到 C_thread2_SyncObjectMethod1_Start 执行结束后执行。
线程访问不同的对象的 synchronized 代码块或者 synchronized 非静态方法的时候都是异步的,同一个类的不同对象的对象锁是互不干扰的。
获取类锁的两种用法

  1. 同步代码块(synchronized(类.class)),锁是小括号()中的类对象(Class 对象)。
  2. 同步静态方法(synchronized static method),锁是当前对象的类对象(Class 对象)。

类锁实际上是通过对象锁实现的,即类的 Class 的对象锁。每个类只有一个 Class 对象,所以每个类只有一个类锁。
下面看一个示例。

package thread;

import java.text.SimpleDateFormat;
import java.util.Date;

public class SyncThread implements Runnable {

    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        if (threadName.startsWith("A")) {
            async();
        } else if (threadName.startsWith("B")) {
            syncObjectBlock1();
        } else if (threadName.startsWith("C")) {
            syncObjectMethod1();
        } else if (threadName.startsWith("D")) {
            syncClassBlock1();
        } else if (threadName.startsWith("E")) {
            syncClassMethod1();
        }
    }

    /**
     * 异步方法
     */
    private void async() {
        try {
            System.out.println(Thread.currentThread().getName() + "_Async_Start: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() + "_Async_End: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 方法中有 synchronized(this|object) {} 同步代码块
     */
    private void syncObjectBlock1() {
        System.out.println(Thread.currentThread().getName() + "_SyncObjectBlock1: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
        synchronized (this) {
            try {
                System.out.println(Thread.currentThread().getName() + "_SyncObjectBlock1_Start: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName() + "_SyncObjectBlock1_End: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * synchronized 修饰非静态方法
     */
    private synchronized void syncObjectMethod1() {
        System.out.println(Thread.currentThread().getName() + "_SyncObjectMethod1: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
        try {
            System.out.println(Thread.currentThread().getName() + "_SyncObjectMethod1_Start: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() + "_SyncObjectMethod1_End: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void syncClassBlock1() {
        System.out.println(Thread.currentThread().getName() + "_SyncClassBlock1: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
        synchronized (SyncThread.class) {
            try {
                System.out.println(Thread.currentThread().getName() + "_SyncClassBlock1_Start: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName() + "_SyncClassBlock1_End: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private synchronized static void syncClassMethod1() {
        System.out.println(Thread.currentThread().getName() + "_SyncClassMethod1: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
        try {
            System.out.println(Thread.currentThread().getName() + "_SyncClassMethod1_Start: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() + "_SyncClassMethod1_End: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
package thread;

public class SyncDemo {
    public static void main(String... args) {
        SyncThread syncThread = new SyncThread();
        Thread A_thread1 = new Thread(syncThread, "A_thread1");
        Thread A_thread2 = new Thread(syncThread, "A_thread2");
        Thread D_thread1 = new Thread(syncThread, "D_thread1");
        Thread D_thread2 = new Thread(syncThread, "D_thread2");
        Thread E_thread1 = new Thread(syncThread, "E_thread1");
        Thread E_thread2 = new Thread(syncThread, "E_thread2");
        A_thread1.start();
        A_thread2.start();
        D_thread1.start();
        D_thread2.start();
        E_thread1.start();
        E_thread2.start();
    }
}

image.png
由结果可以看出,在同一个对象的情况下,类锁表现出来的行为跟对象锁表现出来的行为是一致的。
Class 是一种非常特殊的对象锁,所有的实例共享同一个类。
下面看一个传入不同实例对象的示例。

package thread;

public class SyncDemo {
    public static void main(String... args) {
        SyncThread syncThread = new SyncThread();
        Thread A_thread1 = new Thread(new SyncThread(), "A_thread1");
        Thread A_thread2 = new Thread(new SyncThread(), "A_thread2");
        Thread D_thread1 = new Thread(new SyncThread(), "D_thread1");
        Thread D_thread2 = new Thread(new SyncThread(), "D_thread2");
        Thread E_thread1 = new Thread(new SyncThread(), "E_thread1");
        Thread E_thread2 = new Thread(new SyncThread(), "E_thread2");
        A_thread1.start();
        A_thread2.start();
        D_thread1.start();
        D_thread2.start();
        E_thread1.start();
        E_thread2.start();
    }
}

image.png
执行之后发现 A 类线程依然是异步的,完全不受类锁的影响。其余线程受到类锁的制约,变成同步。
在这里 E_thread1_SyncClassMethod1_Start 先执行,D_thread1、D_thread2、E_thread2 都需要等待 E_thread1 执行完后才能执行。

package thread;

public class SyncDemo {
    public static void main(String... args) {
        SyncThread syncThread = new SyncThread();
        Thread A_thread1 = new Thread(syncThread, "A_thread1");
        Thread A_thread2 = new Thread(syncThread, "A_thread2");
        Thread B_thread1 = new Thread(syncThread, "B_thread1");
        Thread B_thread2 = new Thread(syncThread, "B_thread2");
        Thread C_thread1 = new Thread(syncThread, "C_thread1");
        Thread C_thread2 = new Thread(syncThread, "C_thread2");
        Thread D_thread1 = new Thread(syncThread, "D_thread1");
        Thread D_thread2 = new Thread(syncThread, "D_thread2");
        Thread E_thread1 = new Thread(syncThread, "E_thread1");
        Thread E_thread2 = new Thread(syncThread, "E_thread2");
        A_thread1.start();
        A_thread2.start();
        B_thread1.start();
        B_thread2.start();
        C_thread1.start();
        C_thread2.start();
        D_thread1.start();
        D_thread2.start();
        E_thread1.start();
        E_thread2.start();
    }
}

image.png
如图所示,对象锁和类锁是互不干扰的,异步执行。

8.5 对象锁和类锁的总结

  1. 有线程访问对象的同步代码块时,另外的线程可以访问该对象的非同步代码块
  2. 若锁住的是同一个对象,一个线程在访问对象的同步代码块时,另一个访问对象的同步代码块的线程会被阻塞
  3. 若锁住的是同一个对象,一个线程在访问对象的同步方法时,另一个访问对象同步方法的线程会被阻塞
  4. 若锁住的是同一个对象,一个线程在访问对象的同步代码块时,另一个访问对象同步方法的线程会被阻塞,反之亦然
  5. 同一个类的不同对象的对象锁互不干扰
  6. 类锁由于也是一种特殊的对象锁,因此表现和上述 1,2,3,4 一致,而由于一个类只有一把对象锁,所以同一个类的不同对象使用类锁将会是同步的
  7. 类锁和对象锁互不干扰