1.使用synchronized关键字修饰类或者代码块;安全
2.使用Volatile关键字修饰变量;spa
3.在类中加入重入锁线程
举例子:多个线程在处理一个共享变量的时候,就会出现线程安全问题。(至关于多个窗口卖票的操做)code
非同步状态下:blog
public static void main(String[] args){ Increase increase = new Increase(); int count = 10; while (count != 0){ new Thread(() -> { increase.increasementAndPrint(); }).start(); count --; } } static class Increase { private int i = 0; void increasementAndPrint() { System.out.print(i++ + "\n"); } }
这种状况下可能会致使多个线程输出的i相同:同步
0
0
1
2
3
4
5
6
7
8it
使用同步:class
1.使用synchronized关键字 //保证原子性和有序性 static class Increase { private int i = 0; synchronized void increasementAndPrint() { System.out.println(i++); } } 2.使用volatile //不保证原子性(一个被volatile声明的变量主要有可见性,有序性) static class Increase { private volatile int i = 0; void increasementAndPrint() { System.out.println(i++); } }
volatile关键字不必定可以保证线程安全的问题,其实,在大多数状况下volatile仍是能够保证变量的线程安全问题的。因此,在知足如下两个条件的状况下,volatile就能保证变量的线程安全问题:变量
3.使用重入锁 //保证原子性和有序性 static class Increase { private ReentrantLock reentrantLock = new ReentrantLock(); private int i = 0; void increasementAndPrint() { reentrantLock.lock(); System.out.println(i++); reentrantLock.unlock(); } }