多线程之间如何同步
一、什么是线程安全
当多个线程同时共享同一个全局变量做写的操作时候,可能会受到其他线程的干扰。
二、如何解决线程安全问题
public class TicketThread implements Runnable {
private int count = 100;
@Override
public void run() {
while (count > 0) {
try {
Thread.sleep(30);
} catch (Exception e) {
}
ticket();
}
}
private void ticket() {
if (count > 0) {
System.out.println(Thread.currentThread().getName() + ",正在开始出售:" + (100 - count + 1));
count--;
}
}
public static void main(String[] args) {
TicketThread ticketThread = new TicketThread();
Thread thread1 = new Thread(ticketThread, "窗口1");
Thread thread2 = new Thread(ticketThread, "窗口2");
thread1.start();
thread2.start();
}
}
解决办法:
- 使用java锁的机制 Synchronized、或者Lock锁 还有CAS无锁机制。
- 对于代码中如果在多线程同时执行操作的情况下,可能会受到其他线程的干扰的代码采用锁的机制,在同一个时刻只能保证只有一个线程去执行。也就是只要获取到锁的之后,才能够进入该代码块执行,代码执行完之后释放锁之后其他线程才可以执行。
- 没有获取到锁的线程,则一直会排队阻塞,整个过程是一个悲观状态。
三、Synchronized的基本用法
修饰代码块
private static String lock = "lock";
private static void ticket() {
synchronized (TicketThread.class) {
if (count > 0) {
System.out.println(Thread.currentThread().getName() + ",正在开始出售:" + (100 - count + 1));
count--;
}
}
}
public static void main(String[] args) {
TicketThread ticketThread = new TicketThread();
Thread thread1 = new Thread(ticketThread, "窗口1");
Thread thread2 = new Thread(ticketThread, "窗口2");
thread1.start();
thread2.start();
}
public class TicketThread implements Runnable {
private static int count = 100;
@Override
public void run() {
while (count > 0) {
try {
Thread.sleep(30);
} catch (Exception e) {
}
ticket();
}
}
private static String lock = "lock";
private void ticket() {
synchronized (this) {
if (count > 0) {
System.out.println(Thread.currentThread().getName() + ",正在开始出售:" + (100 - count + 1));
count--;
}
}
}
public static void main(String[] args) {
TicketThread ticketThread = new TicketThread();
Thread thread1 = new Thread(ticketThread, "窗口1");
Thread thread2 = new Thread(ticketThread, "窗口2");
thread1.start();
thread2.start();
}
}
可以定义任意对象作为锁,但是需要注意:如果该方法为普通方法的情况下 可以使用普通对象或者属性作为锁。
如果该方法为静态方法的情况,则必须使用当前类的Class或者是静态属性作为锁。
实例方法
如果在普通方法上加上锁,则表示使用this锁
静态代码块
如果是在静态方法上加上锁,则表示使用当前类的.class锁。
为什么使用锁之后,能够保证线程安全
核心思路:在同一时刻,能够有多个线程操作共享变量。
因为使用锁了之后,多个线程在同时执行该代码的时候,必须要获取到锁,只有获取到锁的情况下,才可以进入到该方法。
比如A线程获取到了之后,B线程则一直阻塞等待,必须等待A线程执行完毕释放了锁之后,B才可以重新进入到获取锁的过程。
简单回顾双重检验锁原理
public class Singleton03 {
private static Singleton03 singleton03;
private Singleton03() {
}
public static Singleton03 getInstance() {
// 上锁(创建该对象) 第一次判断
if (singleton03 == null) {
synchronized (Singleton03.class) {
//第二次判断
if (singleton03 == null) {
singleton03 = new Singleton03();
}
}
}
return singleton03;
}
public static void main(String[] args) {
Singleton03 instance1= Singleton03.getInstance();
Singleton03 instance2= Singleton03.getInstance();
System.out.println(instance1==instance2);
}
}
简单理解锁的可重入性
当一个线程获取到锁之后,在此请求获取该锁的时候,直接可以获取该对象锁。
public class Thread006 implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ",我是子线程");
a();
}
public synchronized void a() {
System.out.println(Thread.currentThread().getName() + ",我是方法A");
b();
}
public synchronized void b() {
System.out.println(Thread.currentThread().getName() + ",我是方法B");
}
}
多线程死锁产生的原因
在同步中嵌套同步,会出现死锁的现象。
public class Thread004 implements Runnable {
private static int count = 100;
private Boolean flag = true;
private Object object = new Object();
@Override
public void run() {
if (flag) {
while (count > 0) {
synchronized (object) {
try {
Thread.sleep(10);
} catch (Exception e) {
}
ticket();
}
}
} else {
while (count > 0) {
ticket();
}
}
}
private synchronized void ticket() {
synchronized (object) {
try {
Thread.sleep(10);
} catch (Exception e) {
}
if (count > 0) {
System.out.println(Thread.currentThread().getName() + ",正在开始出售:" + (100 - count + 1));
count--;
}
}
}
public static void main(String[] args) {
Thread004 thread004 = new Thread004();
new Thread(thread004, "窗口1").start();
try {
Thread.sleep(40);
thread004.flag = false;
} catch (Exception e) {
}
new Thread(thread004, "窗口2").start();
}
}
程序中死锁诊断工具
查找到当前JVM环境变量E:\java8\jdk 找到
jconsole.exe工具
四、Lock锁的基本用法
重入锁(ReentrantLock)
public class Thread005 implements Runnable {
private static int count = 100;
private Lock lock = new ReentrantLock();
@Override
public void run() {
while (count > 0) {
ticket();
}
}
private void ticket() {
try {
Thread.sleep(30);
} catch (Exception e) {
}
try {
lock.lock();
// try {
// } catch (Exception e) {
//
// }
if (count > 0) {
System.out.println(Thread.currentThread().getName() + ",正在开始出售:" + (100 - count + 1));
count--;
}
} catch (Exception e) {
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
Thread005 thread005 = new Thread005();
new Thread(thread005, "窗口1").start();
new Thread(thread005, "窗口2").start();
}
}
读写锁(ReadAndWriteLock)
public class MyTask {
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
/**
* 读读共享
*/
public void read() {
lock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + ",正在开始读取");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + ",正在结束读取");
} catch (Exception e) {
}
lock.readLock().unlock();
}
/**
* 写写互斥
*/
public void write() {
lock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + ",正在开始写入");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + ",正在结束写入");
} catch (Exception e) {
}
lock.writeLock().unlock();
}
public static void main(String[] args) {
MyTask myTask = new MyTask();
// for (int i = 0; i < 10; i++) {
// new Thread(() -> {
// myTask.write();
// }).start();
// }
for (int i =0; i <10;i++){
new Thread(() -> {
myTask.read();
}).start();
new Thread(() -> {
myTask.write();
}).start();
}
}
}
Lock与Synchronized锁的区别
- Synchronized属于java内置的关键字,而lock锁是基于aqs封装的一个锁的框架
- Synchronized当代码执行结束自动释放锁,而lock需要人工释放锁,相对于来说lock锁更加灵活。