一.synchronized
(1)用法:
1.修饰实例方法:
package com.retail.sync;
/**
* @author Tom
*/
public class AccountingSync implements Runnable {
/**
* 共享资源(临界资源)
*/
static int i = 0;
/**
* synchronized 修饰实例方法
*/
public synchronized void increase() {
i++;
}
@Override
public void run() {
for (int j = 0; j < 1000000; j++) {
increase();
}
}
public static void main(String[] args) throws InterruptedException {
AccountingSync instance = new AccountingSync();
Thread t1 = new Thread(instance);
Thread t2 = new Thread(instance);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(i);
}
/**
* 输出结果:
* 2000000
*/
}
package com.retail.sync;
/**
* @author Tom
*/
public class AccountingSyncBad implements Runnable {
static int i = 0;
public synchronized void increase() {
i++;
}
@Override
public void run() {
for (int j = 0; j < 1000000; j++) {
increase();
}
}
public static void main(String[] args) throws InterruptedException {
//new新实例
Thread t1 = new Thread(new AccountingSyncBad());
//new新实例
Thread t2 = new Thread(new AccountingSyncBad());
t1.start();
t2.start();
//join含义:当前线程A等待thread线程终止之后才能从thread.join()返回
t1.join();
t2.join();
System.out.println(i);
/**
* 输出结果:
* 1225662
*/
}
}
2.修饰静态方法:
package com.retail.sync;
public class AccountingSyncClass implements Runnable {
static int i = 0;
/**
* 作用于静态方法,锁是当前class对象,也就是
* AccountingSyncClass类对应的class对象
*/
public static synchronized void increase() {
i++;
}
/**
* 非静态,访问时锁不一样不会发生互斥
*/
public synchronized void increase4Obj() {
i++;
}
@Override
public void run() {
for (int j = 0; j < 1000000; j++) {
increase();
}
}
public static void main(String[] args) throws InterruptedException {
//new新实例
Thread t1 = new Thread(new AccountingSyncClass());
//new心事了
Thread t2 = new Thread(new AccountingSyncClass());
//启动线程
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(i);
/**
* 输出结果:
* 2000000
*/
}
}
3.修饰代码块:
package com.retail.sync;
/**
* @author Tom
*/
public class AccountingSyncBlock implements Runnable {
static AccountingSyncBlock instance = new AccountingSyncBlock();
static int i = 0;
@Override
public void run() {
//省略其他耗时操作....
//使用同步代码块对变量i进行同步操作,锁对象为instance
synchronized (instance) {
for (int j = 0; j < 1000000; j++) {
i++;
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(instance);
Thread t2 = new Thread(instance);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(i);
}
/**
* 输出结果:
* 2000000
*/
}
(1)底层:
Java 虚拟机中的同步(Synchronization)基于进入和退出管程(Monitor)对象实现, 无论是显式同步(有明确的 monitorenter 和 monitorexit 指令,即同步代码块)还是隐式同步都是如此。在 Java 语言中,同步用的最多的地方可能是被 synchronized 修饰的同步方法。同步方法 并不是由 monitorenter 和 monitorexit 指令来实现同步的,而是由方法调用指令读取运行时常量池中方法的 ACC_SYNCHRONIZED 标志来隐式实现的,关于这点,稍后详细分析。下面先来了解一个概念Java对象头,这对深入理解synchronized实现原理非常关键。
在JVM中,对象在内存中的布局分为三块区域:对象头、实例数据和对齐填充
-
实例变量:存放类的属性数据信息,包括父类的属性信息,如果是数组的实例部分还包括数组的长度,这部分内存按4字节对齐。
-
填充数据:由于虚拟机要求对象起始地址必须是8字节的整数倍。填充数据不是必须存在的,仅仅是为了字节对齐,这点了解即可。
二.ReentrantLock
在JDK5.0版本之前,重入锁的性能远远好于synchronized关键字,JDK6.0版本之后synchronized 得到了大量的优化,二者性能也不分伯仲,但是重入锁是可以完全替代synchronized关键字的。除此之外,重入锁又自带一系列高逼格UBFF:可中断响应、锁申请等待限时、公平锁。另外可以结合Condition来使用,使其更是逼格满满。
1.
package com.retail.lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author Tom
*/
public class ReentrantLockTest implements Runnable {
public static ReentrantLock lock = new ReentrantLock();
public static int i = 0;
@Override
public void run() {
for (int j = 0; j < 10000; j++) {
lock.lock(); // 看这里就可以
//lock.lock(); ①
try {
i++;
} finally {
lock.unlock(); // 看这里就可以
//lock.unlock();②
}
}
}
public static void main(String[] args) throws InterruptedException {
ReentrantLockTest test = new ReentrantLockTest();
Thread t1 = new Thread(test);
Thread t2 = new Thread(test);
t1.start();
t2.start();
t1.join();
t2.join(); // main线程会等待t1和t2都运行完再执行以后的流程
System.err.println(i);
}
}
2.可中断
package com.retail.lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author Tom
*/
public class KillDeadlock implements Runnable {
public static ReentrantLock lock1 = new ReentrantLock();
public static ReentrantLock lock2 = new ReentrantLock();
int lock;
public KillDeadlock(int lock) {
this.lock = lock;
}
@Override
public void run() {
try {
if (lock == 1) {
lock1.lockInterruptibly(); // 以可以响应中断的方式加锁
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
lock2.lockInterruptibly();
} else {
lock2.lockInterruptibly(); // 以可以响应中断的方式加锁
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
lock1.lockInterruptibly();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (lock1.isHeldByCurrentThread()) lock1.unlock(); // 注意判断方式
if (lock2.isHeldByCurrentThread()) lock2.unlock();
System.err.println(Thread.currentThread().getId() + "退出!");
}
}
public static void main(String[] args) throws InterruptedException {
KillDeadlock deadLock1 = new KillDeadlock(1);
KillDeadlock deadLock2 = new KillDeadlock(2);
Thread t1 = new Thread(deadLock1);
Thread t2 = new Thread(deadLock2);
t1.start();
t2.start();
Thread.sleep(1000);
t2.interrupt(); // ③
}
}
3.锁申请等待超时
可以使用 tryLock()或者tryLock(long timeout, TimeUtil unit) 方法进行一次限时的锁等待。
package com.retail.lock;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author Tom
*/
public class TryLockTest implements Runnable {
public static ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
try {
if (lock.tryLock(1, TimeUnit.SECONDS)) { // 等待1秒
Thread.sleep(2000); //休眠2秒
} else {
System.err.println(Thread.currentThread().getName() + "获取锁失败!");
}
} catch (Exception e) {
if (lock.isHeldByCurrentThread()) lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
TryLockTest test = new TryLockTest();
Thread t1 = new Thread(test);
t1.setName("线程1");
Thread t2 = new Thread(test);
t1.setName("线程2");
t1.start();
t2.start();
}
}
/**
* 运行结果:
* 线程2获取锁失败!
*/
4.公平锁:
所谓公平锁,就是按照时间先后顺序,使先等待的线程先得到锁,而且,公平锁不会产生饥饿锁,也就是只要排队等待,最终能等待到获取锁的机会。
package com.retail.lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author Tom
*/
public class FairLockTest implements Runnable {
public static ReentrantLock lock = new ReentrantLock(true);
@Override
public void run() {
while (true) {
try {
lock.lock();
System.err.println(Thread.currentThread().getName() + "获取到了锁!");
} finally {
lock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
FairLockTest test = new FairLockTest();
Thread t1 = new Thread(test, "线程1");
Thread t2 = new Thread(test, "线程2");
t1.start();
t2.start();
}
}
/**
* 运行结果:
* 线程1获取到了锁!
* 线程2获取到了锁!
* 线程1获取到了锁!
* 线程2获取到了锁!
* 线程1获取到了锁!
* 线程2获取到了锁!
* 线程1获取到了锁!
* 线程2获取到了锁!
* 线程1获取到了锁!
* 线程2获取到了锁!
* 线程1获取到了锁!
* 线程2获取到了锁!
* 线程1获取到了锁!
* 线程2获取到了锁!
* 线程1获取到了锁!
* 线程2获取到了锁!
* ......(上边是截取的一段)
*/
三.volatile
java内存分为工作内存和主存
工作内存:即java线程的本地内存,是单独给某个线程分配的,存储局部变量等,同时也会复制主存的共享变量作为本地
的副本,目的是为了减少和主存通信的频率,提高效率。
主存:存储类成员变量等
可见性:线程访问变量是否是最新值
package com.retail.vol;
/**
* @author Tom
*/
public class Task implements Runnable {
volatile boolean running = true;
int i = 0;
@Override
public void run() {
while (running) {
i++;
}
}
public static void main(String[] args) throws InterruptedException {
Task task = new Task();
Thread th = new Thread(task);
th.start();
Thread.sleep(10);
task.running = false;
Thread.sleep(10);
System.out.println(task.i);
}
}